Detailed explanation of browser cache issues when jQuery is used in ASP. net mvc, mvcjquery

Source: Internet
Author: User

Detailed explanation of browser cache issues when jQuery is used in ASP. net mvc, mvcjquery

Introduction

Although jQuery provides good support for caching when calling ajax in the browser, it is necessary to know how to use http efficiently.

The first thing to do is to support http get on the server side and define different URLs to output different data (action in MVC ). If you want to use the same address to obtain different data, it is incorrect. an http post cannot be cached because the POST cannot be cached. Many developers use POST mainly for two reasons: it is clear that the data cannot be cached, or the JSON attack is avoided (the data can be infiltrated when the JSON array is returned ).

Cache explanation

The ajax method in the jQuery Global Object provides some options to support caching and Conditional GETs functions.

$.ajax({  ifModified: [true|false],  cache: [true|false],});

The ifModified option defines whether the Conditional GETs function is supported during ajax calls. JQuery will automatically process the header value returned by the server, and then send If-Modified-Since in the header in the subsequent request. This requires our MVC Controller to implement the Conditional GETs function. The Conditional GETs function is used to re-verify expired entries in the http cache context. If jQuery considers that an entry has expired, it first requests the server to use the Conditional GETs function to re-verify the entry. If the server returns the status code 304 (Not modified ), jQuery will re-use the project in the cache. In this way, we can save a lot of traffic to download the page content.

The cache option basically overwrites all cache settings in the http header returned by the server. If the cache option is set to false, jQuery will append a timestamp to the request URL, in order to distinguish the previous URL address, it is correct that the request content is the latest, that is to say, each time the browser receives a new address, it naturally returns the latest data.

Let's look at several scenarios:

Set No-Cache in the server response

The server is king. If the server clearly defines that the response cannot be cached, jQuery cannot do anything. The cache options in ajax will be ignored.

JS Code:

$('#nocache').click(function () {  $.ajax({    url: '/Home/NoCache',    ifModified: false,    cache: true,    success: function (data, status, xhr) {      $('#content').html(data.count);    }  });});

C # code:

Public ActionResult NoCache () {// disable the Cache Response. Cache. SetCacheability (HttpCacheability. NoCache); return Json (new {count = Count ++}, JsonRequestBehavior. AllowGet );}

Set the expiration time in the server response

The server sets the expiration time for data caching. This entry is cached on the client based on the expiration time.

JS Code:

$('#expires').click(function () {  $.ajax({    url: '/Home/Expires',    ifModified: false,    cache: true,    success: function (data, status, xhr) {      $('#content').html(data.count);    }  });});

C # code:

public ActionResult Expires(){  Response.Cache.SetExpires(DateTime.Now.AddSeconds(5));  return Json(new { count = Count++ }, JsonRequestBehavior.AllowGet);}

The client never caches data.

The client determines that the latest data is required each time (the cache cannot be used). That is to say, the cache option in ajaxi is set to false, regardless of how the server is defined, the URL address of each request of jQuery is unique, so that the latest content is obtained every time.

JS Code:

$ ('# Expires_nocache '). click (function () {$. ajax ({url: '/Home/Expires', ifModified: false, cache: false, // The key success: function (data, status, xhr) {response ('{content'}.html (data. count );}});});

C # code:

Public ActionResult Expires () {// no Response is used no matter how the server is set. cache. setExpires (DateTime. now. addSeconds (5); return Json (new {count = Count ++}, JsonRequestBehavior. allowGet );}

The server and client use the Conditional Gets function to verify the cached data.

The client places the entries in the cache and re-verifies them after expiration. The server must implement the Conditional GET function (using the ETags or last modified header ).

JS Code:

$ ('# Expires_conditional '). click (function () {$. ajax ({url: '/Home/expireswithconditional', ifModified: true, // here is the key cache: true, success: function (data, status, xhr) {response ('{content'{.html (data. count );}});});

C # code:

public ActionResult ExpiresWithConditional(){  if (Request.Headers["If-Modified-Since"] != null && Count % 2 == 0)  {    return new HttpStatusCodeResult((int)HttpStatusCode.NotModified);  }  Response.Cache.SetExpires(DateTime.Now.AddSeconds(5));  Response.Cache.SetLastModified(DateTime.Now);  return Json(new { count = Count++ }, JsonRequestBehavior.AllowGet);}

The code in the above MVC action is just an example (non-real code). In actual implementation, the server should be able to know whether the data has been modified since the last response.

Summary

Through these four scenarios in detail, you should understand the Cache Technology of ajax requests, so I will not summarize them.

Http://weblogs.asp.net/cibrax/archive/2012/02/10/hacking-the-browser-cache-with-jquery-and-asp-net-mvc.aspx

The browser cache details for using jQuery in ASP. net mvc above are all the content that I have shared with you. I hope you can give us a reference and support for more.

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.