jquery - JSONP 请求错误处理

标签 jquery ajax json error-handling jsonp

我正在发出 ajax jsonp 请求,但失败错误处理不起作用。如果请求是 404 或 500 则不会处理错误。

我一直在四处寻找答案,但找不到任何东西。似乎有 http://code.google.com/p/jquery-jsonp/ 的解决方案,但我找不到任何有关如何使用它的示例。

function authenticate(user, pass) {       
    $.ajax ({
        type: "POST",
        url: "url",
        dataType: 'jsonp',
        async: false,
        //json object to sent to the authentication url
        data: {"u": userid, "p": pass},

        success: function (data) {
            //successful authentication here
            console.log(data);
        },
        error: function(XHR, textStatus, errorThrown) {
            alert("error: " + textStatus);
            alert("error: " + errorThrown);
        }
    })
}

最佳答案

如果您检查 jQuery.ajax() documentation ,你可以找到:

error

A function to be called if the request fails (...) Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.

因此,您不得不寻找解决方法。您可以指定超时以触发错误回调。这意味着在指定的时间范围内,请求应该成功完成。否则,假设它失败了:

$.ajax({
    ...
    timeout: 5000, // a lot of time for the request to be successfully completed
    ...
    error: function(x, t, m) {
        if(t==="timeout") {
            // something went wrong (handle it)
        }
    }

});

代码中的其他问题...

JSONP (查看 herehere )可用于克服原始策略限制,您不能使用 JSONP POST(请参阅 CORS),因为它只是 doesn't work that way - 它创建一个元素来获取数据,这必须通过 GET 请求完成。 JSONP方案不使用XmlHttpRequest对象,所以不是标准理解的AJAX请求,但内容仍然是动态访问的——对最终用户来说没有区别。

$.ajax({
    url: url,
    type: "GET"
    dataType: "jsonp",
    ...

其次,您提供的数据不正确。您将 javascript 对象(使用对象文字创建)推送到线路上,而不是其序列化的 JSON 表示。创建 JSON 字符串(不是手动,使用例如 JSON.stringify 转换器):

$.ajax({
    ...
    data: JSON.stringify({u: userid, p: pass}),
    ...

最后一期,您已将 async 设置为 false,而文档显示:

Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

关于jquery - JSONP 请求错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19035557/

相关文章:

javascript - 当按下箭头时 jQuery 更改事件在选择上触发

javascript - 如何防止 angularJS 路由?

c# - JSON.NET反序列化自定义日期格式

java - JSONObject toString 和 Base64 性能

javascript - 是否可以将 Handlebars 模板编译为 html?

jquery - 使用 focus-jquery 扩展 div

javascript - 使用 Jquery 加载方法和 Slick 插件

php - 在单页网站中使用 jquery ajax 加载页面时显示进度条

javascript - jQuery 中 $.get 中的变量字段名称

javascript - 使用 Javascript 分配 ColdFusion 客户端变量