错误处理跨域的jQuery ajax调用 [英] Error handling cross domain jquery ajax call

查看:176
本文介绍了错误处理跨域的jQuery ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  $。阿贾克斯({
    键入: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 +。

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+.

这篇关于错误处理跨域的jQuery ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆