Home >Web Front-end >JS Tutorial >How to disable ajax cache to obtain the latest data of the program_javascript skills
When I was working on a project today, almost all submissions were submitted through ajax. When I tested it, I found that the data obtained after each submission was the same. Debugging can eliminate problems with the background code, so the problem must be there. front desk. Every time you clear the cache, you will get new data, so in the final analysis it is a browser cache problem. After struggling for a long time, I finally solved it. Let me summarize it here.
We all know that the main reason why ajax can improve the page loading speed is to reduce the loading of duplicate data through ajax, which means that the data is cached into the memory while loading the data. Once the data is loaded Loading it, as long as we do not refresh the page, the data will always be cached in the memory. When the URL we submit is consistent with the historical URL, there is no need to submit it to the server, that is, there is no need to obtain data from the server. Although this reduces the load on the server and improves the user experience, we cannot obtain the latest data. In order to ensure that the information we read is up to date, we need to disable its caching function.
The solutions are as follows:
1. Add anyAjaxObj.setRequestHeader("If-Modified-Since", "0") before sending the ajax request.
2. Add anyAjaxObj.setRequestHeader("Cache-Control", "no-cache") before sending the ajax request.
3. Add a random number after the URL: "fresh=" Math.random();.
4. Add the time after the URL: "nowtime=" new Date().getTime();.
5. If you are using jQuery, just do $.ajaxSetup({cache:false}). In this way, all ajax on the page will execute this statement and there is no need to save the cache
record.