处理跨域jQuery Ajax调用的错误

3
我正在执行一个跨域GET操作,如下所示。
$.ajax({
    type: "GET",
    url: "http://localhost:65249/api/item/get",
    data: {
        searchText: "test"
    },
    dataType: "jsonp",
    async: false,
    success: function (results) {
        alert(results);
    },
    error: function (jqXHR, error, errorThrown) {
        if (jqXHR.status && jqXHR.status == 401) {
            alert("Unauthorized request");
        } else if (jqXHR.status && jqXHR.status == 404) {
            alert("The requested page not found");
        }
    }
});

但是,在请求完成后,成功或错误块没有被调用。当我在开发者控制台中调试JavaScript时,我收到了错误提示,但JavaScript的错误块没有被调用。

GET http://localhost:65249/api/item/getallproducts?callback=jQuery182028460139059461653_1396510235829&searchText=test&_=1396510674779 401 (Unauthorized)      
2个回答

2

很遗憾,如果您使用的是JSONP,所有返回错误的请求都会静默失败。这是因为JSONP使用脚本标签而不是XmlHttpRequest。如果您希望出现错误提示,您需要使用CORS的XHR。CORS需要在服务器端进行配置,并且只有IE 10+支持客户端。


我已经从ajax调用中删除了"jsonp",并在web api应用程序的web.cofig中配置了cors,现在jquery的错误块正常工作。<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> </customHeaders> </httpProtocol> </system.webServer> - Sandeep

0

错误不适用于跨域调用,请参阅jQuery文档。有关错误信息:

注意:此处理程序不适用于跨域脚本和跨域JSONP请求。

请查看此答案: JSONP请求错误处理


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接