0

下面的代码在收到“401 - Unauthorized”错误时会抛出错误,而不会转到 .fail 或 .always 。有没有办法触发失败并检索来自服务器响应的错误 [myErrorMessage]?

JavaScript

$(document).ready(function() {

    var jqXHR = $.ajax({
        url: "http://[myDomain]/[myPage]",
        dataType: "jsonp",
        jsonpCallback: "myFunction"
    })
        .done(function() { alert("success"); })
        .fail(function() { alert("error"); })
        .always(function() { alert("complete"); });

    function myFunction(data) {
        alert("callback");
    }

});

请求结果

GET http://[myDomain]/[myPage]?callback=myJsFunction&_=1361463044315 HTTP/1.1
Host: [myDomain]
Connection: keep-alive
Accept: */*
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17
Referer: http://[myTotallyDifferentDomain]/Default.aspx
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

响应结果

HTTP/1.1 401 Unauthorized
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 21 Feb 2013 16:10:42 GMT
Content-Length: 67

{"Message":"[myErrorMessage]"}

铬结果

GET http://[myDomain]/[myPage]?callback=myJsFunction&_=1361463044315 401 (Unauthorized) jquery.min.js:5
4

1 回答 1

1

从 jQuery 1.9 开始,JSONP 请求不会因错误而进入失败处理程序,这是记录在案的行为。

据我所知,没有办法解决它。(当然,除了使用代理)

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

于 2013-02-21T16:42:09.020 回答