gpt4 book ai didi

jquery - JSONP 请求错误处理

转载 作者:IT老高 更新时间:2023-10-28 12:47:21 25 4
gpt4 key购买 nike

我正在发出 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com