Summary of methods to prevent jQuery ajax Load from using caching

  • 2020-03-30 02:07:17
  • OfStack

A, usage,
The load function of jquery is a call that requests another file and loads it into the current DOM. The full format of the load method is: load(url, [data], [callback])(note that no parameter is a GET request, and any parameter is a POST method).

* the url: Is the address of the file to be imported.
* data: Optional parameters; Since Load can import not only static HTML files, but also dynamic scripts, such as PHP files, we can put the parameters we want to pass here when we import dynamic files.
* callback: Optional parameters; Is another function that is executed after the load method is called and the server responds.

Caching speeds up page loading to a certain extent, but it often gets us into trouble. In the last article, I briefly introduced the use of Load in jQuery. In practice, we may encounter problems with browser caching. For example, I encountered this problem in IE7.

JQuery Load sample code:


$(document).ready(function(){ 
  $("#labels").load("/blog/categories/labels.html"); 
  //When the page loads, insert the contents of the label.html in the DOM element with ID #labels.
}); 

When I update the label.html, the load method still USES the old label.html in IE7, even if I press the refresh key. The good news is that jQuery provides a way to prevent ajax from using caching, by adding the following statement to the head javascript file.

$.ajaxSetup ({ 
    cache: false //Turn off the corresponding cache for AJAX
}); 

In addition, I will introduce several ways to deal with caching. Note: I have not tested the jQuery load problem, these methods are for reference only!

1. Change file names, such as lables_new.html to lables_new.html.

2. Add a specific time, such as lables.html, to the labels. 20081116. In practice, I use this method to keep files from being cached after I update my CSS /javascript files.

3. Add the following declaration at the top of the labels. HTML file:

< META HTTP - EQUIV = "Pragma" CONTENT = "no - cache" >
< META HTTP - EQUIV = "Expires" CONTENT = "1" >

4. The load function can not only call HTML, but also call script, such as records.php. You can use the header function in the PHP file:


<?php 
header("Cache-Control: no-cache, must-revalidate"); 
?> 

Two other solutions:
Add a time parameter value to the current time in the request path or a hidden field to the form to set the value of the field to the current time.


Related articles: