Home > Web Front-end > JS Tutorial > body text

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

亚连
Release: 2018-05-24 16:54:53
Original
1792 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!