Ajax caching

巴扎黑
巴扎黑Original
2016-11-29 11:48:481394browse

The problem of cached requests in Ajax

In Ajax development, you will encounter the problem of browser caching content. For example, a certain element registers a mouse event (onmouseover). After the event is triggered, the content will be obtained from the server through xmlhttprequest. Without refreshing the page, the browser will cache the content requested for the first time. After the server is updated, the browser will still display the content for the first time.

Usually, this kind of request is a GET request initiated by xmlhttprequest. According to the HTTP specification, GET is used for information retrieval and should be idempotent. That is, the GET method is appropriate when repeated GET requests using the same URL return the same expected results. When there are side effects to a request (for example, when submitting data to register a new user), a POST request should be used instead of a GET. Therefore, the browser will cache the GET request.

Solution:

1. Append a string after the GET request URL to make the server think it is not the same request.

Example "http://www.example.com/index.php?class=aitcle&page=5&_t=" + new Date().getTime()

2. Add xmlHttpRequest.setRequestHeader(" before sending the ajax request If-Modified-Since","0")

Three. Add xmlHttpRequest.setRequestHeader("Cache-Control","no-cache"); before sending the ajax request

Four. Add header when the server responds to the request ("Cache-Control: no-cache, must-revalidate"); (PHP)

5. Use POST instead of GET, the browser will not cache POST

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn