Asp. The Ajax browser caching problem of jquery in net

Source: Internet
Author: User

Let's take a look at the Ajax cache problem for jquery.

jquery ajax request default Request cache is true that is open, The default is False when datatype is script and JSONP. Now I want to read the cache in the browser, because the AJAX request data is very large, request once is enough. But the problem is, in FF, there is no Ajax cache, that is, each time the AJAX request will be triggered, this is not the same as IE. So here's the thing to be aware of, to make a judgment that prevents the Ajax event from triggering.

Function ajax_show (apartid,roomclass,sorttile) {      hx_this_fangxing_num=
Sorttile;       huxing_pic_set_color ();         
  var this_li=$ (' #title_ ' +sorttile);
      var cache=this_li.data ("cache");       if (undefined!=cache) {       var 
Data_arr =cache.split ('-');         xg_pic_links=data_arr[0];//Cache Records      
   layout_pic_links=data_arr[1];
        layout_big_pic_links=data_arr[2];
        product_links=data_arr[3];
           xg_pic_deal_array ();
        xg_show_pic (xg_now_pic_id);         }else{                $.ajax ({///JQ cached cache under FF or will initiate a new request                  type:  "POST"                 url:  "Index.php?m=content&c=index&a=ajax_all_pic",                data:  "apartid=123&
Roomclass=123 ",              datatype: ' Text ',               success: function ( Backdata) {                    this_li.data (' cache ', backdata)//cache record                 &Nbsp;         var data_arr =backdata.split ('-');                     xg_pic_links=data_arr[0];              
          layout_pic_links=data_arr[1];                   
 layout_big_pic_links=data_arr[2];                   
 product_links=data_arr[3];                   
 xg_pic_deal_array ();                     xg_show_pic (xg_now_pic_id);                        
  }        });               } }



Mark by This_li.data (' cache ', backdata)//cache record

Cache interpretation

The AJAX approach in the JQuery Global object provides options to support caching and conditional gets functionality.

$.ajax ({
ifmodified: [True|false],
cache: [True|false],
});



The ifmodified option defines whether the conditional gets feature is supported when Ajax calls. jquery automatically handles the header value returned by the server, named Last-modified, and then sends the if-modified-since in the header in the subsequent request. This requires our MVC controller to implement the conditional gets function. The Conditional gets feature is used in the HTTP cache context to validate expired entries in the cache. If jquery thinks an entry has expired, it first asks the server to conditional the entry using the gets feature, and if the server returns status code 304 (not modified), jquery will reuse the item in the cache, so We can save a lot of traffic to download the page content.

The cache option basically overwrites all the cache-related settings in the HTTP header returned by the server, and if the cache option is set to False, jquery will append a timestamp to the URL after the request to distinguish the URL from the previous address. This is true. The content of the request is up to date, which means that every time the browser receives a new address, the natural return is the latest data.

Let's take a look at a few scenarios:


Set No-cache in server-side response

The server-side is king, and jquery is powerless if the server-side explicitly defines a response response that cannot be cached. 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 caching
Response.Cache.SetCacheability (Httpcacheability.nocache);
Return Json (New {count = count++}, jsonrequestbehavior.allowget);
}



Set expiration time in server-side response

The server-side set expiration time is used to cache data, which is cached by the client based on its expiration date.

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 decides to have the most up-to-date data (not using caching) every time, that is, the cache option in Ajaxi is set to false, and regardless of how the server side is defined, jquery each request URL address is unique, with the goal of getting the latest content each time.

JS Code:

$ (' #expires_nocache '). Click (function () {
$.ajax ({
URL: '/home/expires ',
ifmodified:false ,
Cache:false,//Here is the key
success:function (data, status, XHR) {
$ (' #content '). htm        L (data.count);
}
});
});



C # code:

Public ActionResult Expires ()
{
//No matter how the server side is set,
Response.Cache.SetExpires (DateTime.Now.AddSeconds (5)    );
Return Json (New {count = count++}, jsonrequestbehavior.allowget);
}



Server side and client use conditional gets function to validate cached data

The client places the entries in the cache and validates them after they expire. The server side must implement conditional get functionality (using the header of Etags or last modified).

JS Code:

$ (' #expires_conditional '). Click (function () {
$.ajax ({
URL: '/home/expireswithconditional '),
Ifmodified:true,//Here is the key
cache:true,
success:function (data, status, XHR) {
$ (' #content '). HTML (data.count);
}
});
});



C # code:

Public ActionResult expireswithconditional ()
{
if (request.headers["if-modified-since"]!= null && Co    Unt% 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 MVC action above is just an example (not real code), and in a real implementation, the server side should be able to know whether the data has been modified since the last response.

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.