简体   繁体   中英

ajax call fails on Safari and Firefox without any errors but works on Chrome

I've an ajax call that is executed as part of a function that also redirects the user to another page at the same time. Since this code gets executed on other users' websites, I do not want to use preventDefault() since that can impact the user experience and has been a cause of lot of problems in the past when I tried it. If the call fails a small percentage of times, it not a big deal, but I've seen it perform pretty consistently in all browsers in my experience.

The ajax call looks like following

$.ajax({
    type: 'GET',
    url: 'URL',
    dataType: 'json',
    success: function(data) {
        // stuff
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log("AJAX call failed. Status - " + textStatus);
        console.log("Reason - " + errorThrown); 
    }
});

But for one particular website, I'm seeing some really strange behavior. Its executing as expected in Chrome. But I'm seeing the following in my console for Safari and Firefox.

AJAX call failed. Status - error. 
Reason -

The readyState and status properties on the jqXHR object are both 0.

The URL does NOT point to another domain so I'm sure that its not because of the Cross-Origin policy.

Doing some research on other similar StackOverflow questions like this one and this one , it seems like the browser redirects before the ajax call is complete.

I'm curious about the following things.

  • Why do I only see this behavior on Safari and Firefox? Is Chrome just better at remembering asynchronous requests and making sure that it doesn't just drop pending callbacks?
  • Can it be fixed without using preventDefault ?

I found myself struggling with a similar problem today. The call works fine in IE and Chrome, but doesn't work in Safari and Firefox (despite the actual network request returning 200 success, the data just disappeared).

Wrapping my AJAX call inside a $(document).ready() function seemed to fix the problem.

Originally I had it outside the ready function because the site I'm working on uses the History API to navigate between pages (and loading new content triggers the ready function, duplicating already loaded functions, whereas I only wanted to make this AJAX call once per site visit).

So now I'm re-fetching the same data each page load instead of only once, but at least it's working in all browsers. Hopefully this helps you if you've landed on this question from Google like I did.

No idea why Firefox and Safari can't complete the AJAX call correctly before the DOM is ready...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM