jQuery AJAX producing 304 responses when it shouldn't

前端 未结 3 1250
粉色の甜心
粉色の甜心 2020-12-14 06:53

This really has me scratching my head. Namely because it only happens in IE, not Firefox, and I was under the impression that jQuery was effectively browser neutral. I\'ve b

相关标签:
3条回答
  • 2020-12-14 07:29

    Cache busting is the solution!

    In my case the application used a single service call with a custom header as a proxy to bridge the browser to the private part of the server (every call went to the same url, but used a custom header to tell the proxy service which service to pass it onto). Everything worked fine on Chrome and FF but IE kept returning data from the first call made on the page. cache=false option in jQuery.ajax was the fix since IE just looked at the same url being called, didn't even bother looking at whether any custom headers were used, or whether different data was even being passed in the body, and just said "oh, I know this one, here.." and gave back the response of the first call. With the cache busting technique the url looks different to IE so it sent it through.

    0 讨论(0)
  • 2020-12-14 07:35

    I cannot see, you specifying the ajax request as a POST. So basically add:

    $.ajax({ type: 'POST' });
    

    and if that still fails (due to some browser AJAX weirdness), you could try setting cache: false:

    $.ajax({ type: 'POST', cache: false });
    

    Btw, all cache: false does, is adding some random stuff to the request URL.

    EDIT1:

    Regarding the

    ... and I was under the impression that jquery.ajax was designed to, unless otherwise instructed, not generate 304 responses

    jQuery istn't generating any responses here. And the 304-header is just an HTTP header. HTTP AJAX requests are ordinary HTTP requests and may return any valid header. If the server responds with 304, the XHR object will simply serve up the locally cached response from the server. It's completely transparent for the user, though.

    EDIT2:

    Removed the advice about preventing caching. Seems like Voodoo to me.

    EDIT3:

    Added that bit in again because it apparently was necessary. Looking around the web, IE seems to be illegally caching AJAX POSTs to some extent.

    0 讨论(0)
  • 2020-12-14 07:41
    1. Always use POST for calls to methods that modify state, not GET. This should be enough in this instance to prevent IE caching the request.
    2. IE aggressively caches ajax requests (see http://www.dashbay.com/2011/05/internet-explorer-caches-ajax/ and https://blog.httpwatch.com/2009/08/07/ajax-caching-two-important-facts/). To prevent this, you can:
      1. Add a cache busting parameter ($.ajaxSetup({ cache: false }); does this automatically.
      2. Always use POST requests (probably not appropriate in most cases).
      3. Turn on cache headers for AJAX requests server side. The first link demonstrates how to do this using in groovy. Similar methods should apply to any framework.
    0 讨论(0)
提交回复
热议问题