Google Analytics İzleme

14 Haziran 2012

MVC 3 - Jquery JSON ajax isteklerinde önbelleklemeyi (caching) engelleme

İnternet Explorer; ajax ile bir adrese aynı parametrelerle çağırım yapıldığında sonucu önbelleğe alır, sonraki çağrımlar da ise sonucu bu önbellekten getirmektedir. Önbellekten gelmesini engelleyip, sürekli ajax sorgusunu sunucuya yapmak için çeşitli yöntemler uygulanmaktadır, bunlar aşağıdaki gibidir:

--

Which browsers cache the request?

If you do something like this to load the JSON data:
1$.getJSON('/path/to/my/json/file.js'function(data) {
2    // do something now that the data is loaded
3});
then the browser will load the JSON file and then run the function to do something with it.
The following notes about which browsers cache and don't cache are accurate from my own testing in current released versions of the browsers as at March 12th 2010.
If you run the function again on the same page without reloading the page, the following browsers will not request the JSON file again, and nor will they on subsequent page requests:
  • Firefox
  • Internet Explorer
The following browsers will request the file again each time, whether it's requested for a second time on the same page or on a page loaded later:
  • Opera
  • Safari
And finally, the following will request the file again each time if it's requested on the same page, but willload it from the cache when requested from subsquent pages:
  • Chrome
When they don't cache, they still won't even if using $.ajax to fetch the data and setting the cache property to true.

How to make sure the file is not cached

Should you need to ensure the JSON file is loaded again each time it is requested without caching (in the event you need to load the same file again on the same page), then you need to provide either a unique URL or use a $.ajax call and set the cache property to false.
To use $.getJSON and prevent caching, add a unique value to the query string using the Date() object as shown below. Each time the function is run the url will be different.
1$.getJSON('/path/to/my/json/file.js?' new Date().getTime(), function(data) {
2    // do something now that the data is loaded
3});
To use the $.ajax function instead, do this:
1$.ajax({
2    cache: false,
3    success: function(data) {
4        // do something now that the data is loaded
5    },
6    url: '/path/to/my/json/file.js'
7});
Another way to change the caching behavior is to change the AJAX settings like so:
1$.ajaxSetup({ cache:false });
And then do the $.getJSON() request in the normal way. Be aware that this will affect all subsequent AJAX requests unless changed again. 

--
Kaynak:
http://www.electrictoolbox.com/jquery-json-ajax-caching/

Hiç yorum yok: