Instructions on how to solve the cache problem of Ajax request results

Source: Internet
Author: User

By default, IE caches the Ajax request results for the request address. In other words, before the cache expires, multiple Ajax requests initiated for the same address will only be sent to the server for the first time. In some cases, this default caching mechanism is not what we want (such as obtaining real-time data). This article will briefly discuss this issue and introduce several solutions.
Directory
I. Problem Reproduction
2. Solve the problem by adding a suffix to the URL address
Iii. Solve the problem through Ajax settings of JQuery
4. solving problems through custom response
I. Problem Reproduction
We use an ASP. net mvc application to reproduce the cache of IE Ajax request results. In an empty ASP. net mvc application, we define the next default HomeController, which contains an Action method GetCurrentTime that returns the current time.

Copy codeThe Code is as follows: public class HomeController: Controller
{
Public ActionResult Index ()
{
Return View ();
}
Public string GetCurrentTime ()
{
Return DateTime. Now. ToLongTimeString ();
}
}

The View corresponding to the Index of the default Action method is defined as follows. We use JQuery to call the GetCurrentTime operation in Ajax every five seconds and display the returned results.Copy codeThe Code is as follows: <! DOCTYPE html>
<Html>
<Head>
<Title> @ ViewBag. Title </title>
<Script type = "text/javascript" src = "@ Url. Coutent (" ~ /Scripts/jquery-1.7.1.min.js ")"> </script>
<Script type = "text/javascript">
$ (Function (){
Window. setInterval (function (){
$. Ajax ({
Url: '@ Url. Action ("GetCurrentTime ")',
Success: function (result ){
$ ("Ul"). append ("<li>" + result + "</li> ");
}
});
},5000 );
});
</Script>
</Head>
<Body>
<Ul> </ul>
</Body>
</Html>

Running the program in different browsers produces different output results. As shown in, the real-time is displayed in Chrome, but the time displayed in IE is the same.

2. Solve the problem by adding a suffix to the URL address
Because the results returned by IE for Ajax requests are cached based on the request address, if you do not want this cache mechanism to take effect, we can add different suffixes to the request address in each request to solve this problem. In this example, we use the following code to add a query string based on the current time for the request address. After the program is run again, IE will display the real-time.

Copy codeThe Code is as follows: <! DOCTYPE html>
<Html>
<Head>
<Script type = "text/javascript">
$ (Function (){
Window. setInterval (function (){
$. Ajax ({
Url: '@ Url. Action ("GetCurrentTime ")? '+ New Date (). toTimeString (),
Success: function (result ){
$ ("Ul"). append ("<li>" + result + "</li> ");
}
});
},5000 );
});
</Script>
</Head>
</Html>

Iii. Solve the problem through Ajax settings of jQuery
In fact, jQuery has Ajax settings for this purpose. We only need to call the $. ajaxSetup method as follows to disable the cache mechanism of Ajaz.

Copy codeThe Code is as follows: <! DOCTYPE html>
<Html>
<Head>
<Script type = "text/javascript">
$ (Function (){
$. AjaxSetup ({cache: false });

Window. setInterval (function (){
$. Ajax ({
Url: '@ Url. Action ("GetCurrentTime ")',
Success: function (result ){
$ ("Ul"). append ("<li>" + result + "</li> ");
}
});
},5000 );
});
</Script>
</Head>
</Html>

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

4. solving problems through custom response
We can control the browser's result cache through the request response. Therefore, we define the next ActionFilter named NoCacheAttribute. In the OnActionExecuted method implemented, we call the SetCacheability method of the current HttpResponse to set the cache option to NoCache. After the NoCacheAttribute feature is applied to the GetCurrentTime method, running our program can still get real-time in IE.

Copy codeThe Code is as follows: 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)
{}
}

The actual NoCacheAttribute feature controls the Cache-Control header of a message and sets it to "no-cache", indicating that the browser does not Cache the result. The Response Message for the GetCurrentTime request is as follows:

Copy codeThe Code is as follows: HTTP/1.1 200 OK
Server: ASP. NET Development Server/10.0.0.0
Date: Thu, 03 Jan 2013 12:54:56 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 4.0
Cache-Control: no-cache

Pragma: no-cache
Expires:-1
Content-Type: text/html; charset = UTF-8
Content-Length: 10
Connection: Close

8:54:56

Keep yourself in mind and look down on China

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.