Home > Article > Backend Development > ajax2—solve caching problems—php (28)
5. ajax quick start
ajax code:
Php program:
6. Send data
When making an Ajax get request, the data to be sent needs to be appended to the end of the url
When making an Ajax post request, the data to be sent needs to be placed in the parameters of the send method
Ajax code:
Php code:
Deliberately write the requested URL wrong. We found that even if a URL that does not exist is requested, the status code of the ajax object will eventually be equal to 4, and the corresponding statement will be executed, and we hope that if the request is an error page , then the corresponding statement should not be executed
Make some corresponding modifications
Use ajax to calculate the sum of two numbers
7. Solve the cache problem
Above questions:
Change addition in php to subtraction
If the previous request parameter is used, it is still found to be addition. If it is a new request parameter, it is subtraction.
Solution 1: Random numbers
Math.random();
Generate a js random number after the url, so that the URL requested this time is unique, so the latest data will be returned every time you request it
However, we know that this method does not fundamentally solve the caching problem, it just generates a large number of cache files
One more thing: random numbers do not guarantee that this URL is absolutely unique
Solution 2:
time
new Date().getTime(); //Get the millisecond timestamp
The above method directly appends the timestamp to the url to make the current url unique. In terms of execution, this method will always be unique
However, it will still generate a large number of cache files under temporary files.
Solution 3. Set request header
setRequestHeader("If-Modified-Since","0");
Principle: Use the ajax object to set the http request header information before sending the http request, indicating that the last modification time of the resource currently being requested is "0". After the server gets this time, it will be compared with the last modification of the file on the server. The time is compared, and if they are different, the latest execution result is returned.
This way, there is always only one cache file in the end.
Solution4. Set response header
header("Cache-Control: no-cache, must-revalidate");
Use PHP's header function to write data to the response header. What is written is to tell the client: Do not cache this result.
This approach can fundamentally solve the caching problem without generating any cache files.
Example question:
Verify whether the username can be used
The above introduces ajax2 - solving cache problems - php (28), including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.