我正在发出 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 (查看 here 和 here )可用于克服源策略限制,您不能使用 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/48746481/