Disables ajax caching methods for getting the latest data from a program

  • 2020-03-29 23:51:41
  • OfStack

During the project today, almost all the submissions were submitted through ajax. During the test, I found that the data obtained after each submission was the same. Debugging could eliminate problems in the background code, so the problem must be in the foreground. Each time you clear the cache, you get a new piece of data, so it all boils down to browser caching. Tangled for a long time, finally resolved, here is a summary.

We all know that ajax can improve the speed of page loads the main reason is that through ajax reduces duplicate data load, that is to say, at the same time of loading data to data cache memory, once the data is loaded, as long as we have not refresh the page, these data will be cached in memory, when we submit the URL of the URL is consistent with history, there is no need to submit to the server, also is not need from the server to get the data above, though this reduced server load to improve the user experience, but we can't get the latest data. In order to ensure that the information we read is up to date, we need to disable its caching.

The solutions are as follows:

1, before the ajax request plus anyAjaxObj setRequestHeader (" the if-modified-since ", "0").

2, in front of the ajax request plus anyAjaxObj. SetRequestHeader (" cache-control ", "no - Cache").

Add a random number after the URL: "fresh=" + math.random (); .

4. Add "nowtime=" + new Date(). .

5. If you are using jQuery, you can just set up $.ajaxsetup ({cache:false}). So all the ajax on the page will execute this statement without the need to save the cache

Save record.


Related articles: