How to tell if an XMLHTTPRequest hit the browser cache

后端 未结 5 1568
别跟我提以往
别跟我提以往 2020-12-25 12:13

If it possible to tell (within javascript execution) if a GET XMLHTTPRequest hit the browser cache instead of getting its response from the server?

5条回答
  •  遥遥无期
    2020-12-25 13:11

    When making an ajax request, You get the response code

    if (request.readyState == 4) {
         if (request.status == 200) { // this number.
           ...
    

    status 200 means you are getting a fresh copy of the data:

    The request has succeeded. The information returned with the response is dependent on the method used in the request -

    status 304 means the data has not changed and you will get it from the browser cache:

    If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code.

    Read more on Status Code

    Update:
    You can add a cache buster to your URL to guarantee that you always hit the server:

    var ajaxUrl = "/path?cache="+(Math.random()*1000000);
    

提交回复
热议问题