jQuery ajax error callback not firing

2019-04-28 15:52发布

问题:

I am requesting a URL with ajax that results in a HTTP header code 500. I would expect this to trigger the error function:

    $.ajax({
  url: "http://xxx",
  dataType: "jsonp",
  crossDomain: true,
  success: function( data ) {
        alert('success');
  },
  error: function () {
        alert('error');
  }
});

This works in safari, but fails in chrome and firefox.

What am I doing wrong?

This is the latest jquery 1.4.X, for reasons I cannot upgrade to later versions..

The response sends a HTTP code 500, content type application/json and contents:

jsonp1310063232212({"error":{"reason":"User not found"}})

回答1:

It looks like crossDomain: wasn't added until jQuery 1.5.

http://api.jquery.com/jQuery.ajax/

crossDomain(added 1.5)

Default: false for same-domain requests, true for cross-domain requests.

If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain

Like Martin Larente suggested in his comment, it could be an issue with how different browsers or jQuery detects/reports JSONP errors.



回答2:

As stated on JQuery documentation [1] the error handler is not called for cross-domain script and JSONP requests. It worked (not always) on older versions of JQuery.

I solve using a compact and effective plugin that include a nice error handler: http://code.google.com/p/jquery-jsonp/

Download it and add it to head:

<script src="javascripts/jquery.jsonp-2.2.0.min.js" type="text/javascript"></script>

Then you can use function $.jsonp() similar to $.ajax():

$.jsonp({
    url: "http://xxx?callback=?",
    data: {
        var: 'test'
    },
    cache: false,
    success: function(data, textStatus) {
        // ...
    },
    error: function(xOptions, textStatus) {
        console.log('Error');
        // ...
    }
});

[1] http://api.jquery.com/jQuery.ajax/



回答3:

There seems to be outstanding issues with this see. Abort JSONP ajax request with jQuery