错误处理跨域的jQuery ajax调用错误、jQuery、ajax

由网友(牵猫散步的鱼)分享简介:我执行一个跨域获取操作如下所示。 $。阿贾克斯({键入:GET,网址:HTTP://本地主机:65249 / API /项目/获取,数据: {sea​​rchText:测试},数据类型:JSONP异步:假的,成功:函数(结果){警报(结果);},错误:函数(jqXHR,错误errorThrown){如果(jqXHR.s...

我执行一个跨域获取操作如下所示。

  $。阿贾克斯({
    键入:GET,
    网址:HTTP://本地主机:65249 / API /项目/获取,
    数据: {
        sea​​rchText:测试
    },
    数据类型:JSONP
    异步:假的,
    成功:函数(结果){
        警报(结果);
    },
    错误:函数(jqXHR,错误errorThrown){
        如果(jqXHR.status&安培;&安培; jqXHR.status == 401){
            警报(未经授权的请求);
        }否则如果(jqXHR.status&安培;&安培; jqXHR.status == 404){
            警报(请求的页面没有找到);
        }
    }
});
 

但成功或错误块是没有得到所谓的请求完成后。当我调试在开发者控制台中的Java脚本我收到的错误,但JavaScript的错误块是没有得到调用。

  GET http://localhost:65249/api/item/getallproducts?callback=jQuery182028460139059461653_1396510235829&searchText=test&_=1396510674779 401
 

解决方案

不幸的是,如果你使用的是JSONP,返回一个错误的所有请求静静的失败。这是因为JSONP使用,而不是XmlHtt prequest的脚本标记。如果你想错误解雇,你需要使用XHR与CORS。 CORS需要在服务器端配置,以及它的工作原理客户端只能在IE 10 +。

JQuery Ajax

I am performing one cross domain get operation as shown below.

$.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");
        }
    }
});

But success or error block is not getting called after request is completed. when i debug java script in developer console i am receiving error but error block of javascript is not getting called.

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

解决方案

Unfortunately, if you are using JSONP, all requests that return an error fail silently. This is because JSONP uses a script tag instead of XmlHttpRequest. If you want errors to fire, you need to use XHR with CORS. CORS needs to be configured on the server side, and it works client side only in IE 10+.

阅读全文

相关推荐

最新文章