Proper way to handle 304 not modified in jQuery ajax

后端 未结 2 1951
Happy的楠姐
Happy的楠姐 2021-02-18 23:02

As of jQuery 1.5, the ajax methods now correctly handle 304 Not Modified responses by calling the success() handler, as per the W3C spec for XMLHTTPRequest. This allows your ap

相关标签:
2条回答
  • 2021-02-18 23:07

    I've just spotted the obvious flaw in my question....I was assuming that the data was always text, so using jqXHR.responseText in preference to the data argument made sense.

    But in the case that the dataType is JSON, JSONP, script etc...if the data returned in a 304 Not Modified response comes back as undefined, you'd need to convert the jqXHR.responseText from a string to the desired type first, eg.

    if (data === undefined) {
      data = $.parseJSON(jqXHR.responseText);
    }
    

    ...and you'd only want to do this (potentially expensive) conversion when you need really to.

    Kinda makes sense now that I think about it...data is always going to be what came back from the server (which in some cases might not be undefined for a 304...eg. the server could return some additional text/html); which allows the developer the flexibility to choose what they want to do in the event of a 304, eg.

    • Display the response from the server (if any)
    • Use the jqXHR.responseText
    • Do something else entirely...
    0 讨论(0)
  • 2021-02-18 23:24

    Depending on context, you could use the cache parameter to the ajax request:

    $.ajax({
        url: ".....",
        dataType: "json",
        type: "GET",
            cache: false,
        contentType: "application/json",
            success: function (data, textStatus) {
                console.log("RECV: " + data);
            }
        });
    

    That's working for me.

    0 讨论(0)
提交回复
热议问题