How to solve the caching problem of Ajax Request Results _ Practical skills

Source: Internet
Author: User
Tags setinterval

By default, IE caches the results of the AJAX request for the request address. In other words, before the cache expires, multiple AJAX requests for the same address are actually sent to the server for the first time. In some cases, this default caching mechanism is not what we want (such as getting real-time data), this article simply discusses the problem and introduces several solutions.
Directory
I. Recurring problems
Second, to solve the problem by adding a suffix to the URL address
Third, through jquery Ajax settings to solve the problem
Iv. Solving problems by customizing responses
I. Recurring problems
We use a asp.net MVC application to reproduce IE caching for AJAX request results. In an empty asp.net MVC application we defined the following default HomeController, which contains an action method getcurrenttime that returns the current time.

Copy Code code as follows:

public class Homecontroller:controller
{
Public ActionResult Index ()
{
return View ();
}
public string GetCurrentTime ()
{
return DateTime.Now.ToLongTimeString ();
}
}

The default action method index corresponds to the view definition as follows. We use the JQuery method to invoke the GetCurrentTime operation in Ajax mode every 5 seconds and display the returned results.
Copy Code code as follows:

<! DOCTYPE html>
<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>
<body>
<ul></ul>
</body>

Running the program in a different browser results in different output, as shown in the following illustration, the Chrome browser can display real-time time, but the time displayed in IE is the same.

Second, to solve the problem by adding a suffix to the URL address
Because the result of IE's return for AJAX requests is cached based on the request address, if you do not want the caching mechanism to take effect, we can resolve the problem by adding a different suffix to the request address on each request. For this example, we use the following code to add a query string based on the current time for the request address, and then run the program again, IE will display the real-time time.

Copy Code code as follows:

<! DOCTYPE html>
<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>

Third, through jquery Ajax settings to solve the problem
In fact, jquery has an AJAX setting for this, and we just need to call the $.ajaxsetup method in the following way to disable the Ajaz caching mechanism.

Copy Code code as follows:

<! DOCTYPE html>
<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>

In fact, this mechanism of jquery is also implemented by adding a different query string suffix to the request address, which can be confirmed by a fiddler interception request.

Iv. Solving problems by customizing responses
We can control the browser's caching of results by responding to the request, and we have defined the following as a actionfilter named Nocacheattribute. In the onactionexecuted method of implementation, we call the current HttpResponse SetCacheability method 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 time in IE.

Copy Code code 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 attribute ultimately controls the Cache-control header of the message message and sets it to "No-cache", which instructs the browser not to cache the results. The response message for the GetCurrentTime request is shown below:

Copy Code code as follows:

http/1.1 OK
Server:ASP.NET Development server/10.0.0.0
Date:thu, 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 PM

Keep your own heart, watch the light glitz

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.