Home Web Front-end JS Tutorial A brief analysis of IE's caching problem for Ajax request results

A brief analysis of IE's caching problem for Ajax request results

May 24, 2018 pm 04:54 PM
ajax ie result

We use an ASP.NET MVC application to reproduce IE's caching of Ajax request results. In an empty ASP.NET MVC application we define a default HomeController as follows, which contains an Action method GetCurrentTime that returns the current time.

By default, IE caches the results of Ajax requests based on the request address. In other words, before the cache expires, only the first time of multiple Ajax requests initiated for the same address will actually be sent to the server. In some cases, this default caching mechanism is not what we want (such as obtaining real-time data). This article will briefly discuss this problem and introduce several solutions.

Directory

1. Reproduce the problem

2. Pass the URL Solving the problem by adding a suffix to the address

3. Solving the problem through JQuery’s Ajax settings

4. Through customization Response to solve the problem

1. Problem reproduction

We use an ASP.NET MVC application to reproduce IE's caching of Ajax request results. In an empty ASP.NET MVC application we define a default HomeController as follows, which contains an Action method GetCurrentTime that returns the current time.

 public class HomeController Controller
 {
  public ActionResult Index()
  {
   return View();
  }
  
  public string GetCurrentTime()
  {
   return DateTime.Now.ToLongTimeString();
  }
 }
Copy after login

The View corresponding to the default Action method Index is defined as follows. We use the JQuery method to call the GetCurrentTime operation in Ajax every 5 seconds and display the returned results.

<!DOCTYPE html>
 <html>
  <head>
   <title>@ViewBag.Title</title> 
   <script type="text/javascript" src="@Url.Coutent(“~/Scripts/jquery-...min.js”)"></script>
   <script type="text/javascript">
    $(function () {
     window.setInterval(function () {
      $.ajax({
       url&#39;@Url.Action("GetCurrentTime")&#39;,
       success function (result) {
        $("ul").append("<li>" + result + "</li>");
       }
      });
     }, );
    });
   </script>
  </head>
  <body> 
   <ul></ul>
  </body>
 </html>
Copy after login

Running this program in different browsers will get different output results. As shown in the figure below, the real-time time can be displayed in the Chrome browser, but The time displayed in IE is the same.

##2. Solve the problem by adding a suffix to the URL address

Since the results returned by IE for Ajax requests are cached based on the request address, if we do not want this caching mechanism to take effect, we can add a different suffix to the request address in each request to solve this problem. For this example, we use the following code to add a query string based on the current time to the request address. After running the program again, the real-time time will be displayed in IE.

 <!DOCTYPE html>
 <html>
  <head>  
   <script type="text/javascript">
    $(function () {
     window.setInterval(function () {
      $.ajax({
       url&#39;@Url.Action("GetCurrentTime")?&#39;+ new Date().toTimeString() ,
       success function (result) {
        $("ul").append("<li>" + result + "</li>");
       }
      });
     }, );
    });
   </script>
  </head>
 </html>
Copy after login

3. Solve the problem through jQuery’s Ajax settings

In fact, jQuery has an Ajax setting for this. We only need to call the $.ajaxSetup method as follows to disable Ajaz's caching mechanism.

 <!DOCTYPE html>
 <html>
  <head>  
   <script type="text/javascript">
    $(function () {
     $.ajaxSetup({ cache false }); 
     window.setInterval(function () {
      $.ajax({
       url&#39;@Url.Action("GetCurrentTime")&#39;,
       success function (result) {
        $("ul").append("<li>" + result + "</li>");
       }
      });
     }, );
    });
   </script>
  </head>
 </html>
Copy after login

In fact, this mechanism of jQuery is also implemented by adding different query string suffixes to the request address, which can be confirmed by requests intercepted by Fiddler .

4. Solve the problem through customized responses

We can control the browser’s caching of results through the requested response, for So we define the following ActionFilter named NoCacheAttribute. In the implemented OnActionExecuted method, we call the SetCacheability method of the current HttpResponse to set the cache option to NoCache. After the NoCacheAttribute attribute is applied to the GetCurrentTime method, we can still get the real-time time when running our program in IE.

public class HomeController Controller
 {
  public ActionResult Index()
  {
   return View();
  }
  
  [NoCache] 
  public string GetCurrentTime()
  {
   return DateTime.Now.ToLongTimeString();
  }
 }
 public class NoCacheAttribute FilterAttribute, IActionFilter
 {
  public void OnActionExecuted(ActionExecutedContext filterContext)
  {
   filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
  }
 
  public void OnActionExecuting(ActionExecutingContext filterContext)
  {}
 }
Copy after login

The actual NoCacheAttribute attribute ultimately controls the Cache-Control header of the message message and sets it to "no-cache", instructing the browser not to cache the result. cache. The following is the response message to the GetCurrentTime request:

 HTTP/. OK
 Server ASP.NET Development Server/...
 Date Thu, Jan GMT
 X-AspNet-Version ..
 X-AspNetMvc-Version .
 Cache-Control no-cache 
 Pragma no-cache
 Expires -
 Content-Type text/html; charset=utf-
 Content-Length 
 Connection Close
 PM
Copy after login

The above is what I compiled for everyone. I hope it will be useful to everyone in the future. helpful.

Related articles:

Writing lightweight ajax components 02--A brief analysis of AjaxPro

##What to do if the Ajax request session fails Solve


Solve the forward and backward problem of ajax based on Jquery.history


The above is the detailed content of A brief analysis of IE's caching problem for Ajax request results. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

What should I do if win11 cannot use ie11 browser? (win11 cannot use IE browser) What should I do if win11 cannot use ie11 browser? (win11 cannot use IE browser) Feb 10, 2024 am 10:30 AM

More and more users are starting to upgrade the win11 system. Since each user has different usage habits, many users are still using the ie11 browser. So what should I do if the win11 system cannot use the ie browser? Does windows11 still support ie11? Let’s take a look at the solution. Solution to the problem that win11 cannot use the ie11 browser 1. First, right-click the start menu and select "Command Prompt (Administrator)" to open it. 2. After opening, directly enter "Netshwinsockreset" and press Enter to confirm. 3. After confirmation, enter "netshadvfirewallreset&rdqu

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

How to cancel the automatic jump to Edge when opening IE in Win10_Solution to the automatic jump of IE browser page How to cancel the automatic jump to Edge when opening IE in Win10_Solution to the automatic jump of IE browser page Mar 20, 2024 pm 09:21 PM

Recently, many win10 users have found that their IE browser always automatically jumps to the edge browser when using computer browsers. So how to turn off the automatic jump to edge when opening IE in win10? Let this site carefully introduce to users how to automatically jump to edge and close when opening IE in win10. 1. We log in to the edge browser, click... in the upper right corner, and look for the drop-down settings option. 2. After we enter the settings, click Default Browser in the left column. 3. Finally, in the compatibility, we check the box to not allow the website to be reloaded in IE mode and restart the IE browser.

See all articles