jQuery JSONP 请求错误处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19035557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSONP request error handling
提问by Adrian Mojica
I'm making an ajax jsonp request, but the failure error handling wont work. If the request is 404 or 500 it won't handle the error.
我正在发出一个 ajax jsonp 请求,但失败错误处理不起作用。如果请求是 404 或 500,它不会处理错误。
I've been looking around to find an answer to this, but can't find anything. There seems to be a solution with http://code.google.com/p/jquery-jsonp/, but I can't find any examples on how to use it.
我一直在四处寻找这个问题的答案,但找不到任何东西。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);
}
})
}
采纳答案by shyammtp
Two ways to handle error,
两种处理错误的方法,
There is no error handling for cross domain JSONP requests. Use jsonp plug-in available on Github https://github.com/jaubourg/jquery-jsonpthat provides support for error handling.
jQuery ajax Timeout - Timeout after a reasonable amount of time to fire the error callback because it might have failed silently. You may not know what the actual error (or error status) was but at least you get to handle the error
跨域 JSONP 请求没有错误处理。使用 Github https://github.com/jaubourg/jquery-jsonp上提供的jsonp 插件,该插件 提供对错误处理的支持。
jQuery ajax 超时 - 在触发错误回调的合理时间后超时,因为它可能已静默失败。您可能不知道实际的错误(或错误状态)是什么,但至少您可以处理错误
回答by jwaliszko
If you check jQuery.ajax() documentation, you can find:
如果您查看jQuery.ajax() 文档,您可以找到:
error
A function to be called if the request fails (...) Note: This handler is notcalled for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.
错误
请求失败时要调用的函数 (...)注意:跨域脚本和跨域 JSONP 请求不会调用此处理程序。这是一个 Ajax 事件。
Because of that, you're forced to find workaround. You can specify timeout to trigger an error callback. It means that within specified time frame the request should be successfully completed. Otherwise, assume it has failed:
因此,您不得不寻找解决方法。您可以指定超时以触发错误回调。这意味着应在指定的时间范围内成功完成请求。否则,假设它失败了:
$.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)
}
}
});
Other issues in your code...
您的代码中的其他问题...
While JSONP(look hereand here) can be used to overcome origin policy restriction, you can't POST using JSONP (see CORSinstead) because it just doesn't work that way- it creates a element to fetch data, which has to be done via GET request. JSONP solution doesn't use XmlHttpRequest object, so it is not an AJAX request in the standard way of understanding, but the content is still accessed dynamically - no difference for the end user.
虽然JSONP(查看此处和此处)可用于克服源策略限制,但您不能使用 JSONP(请参阅CORS)进行POST,因为它不能那样工作- 它创建了一个元素来获取数据,这必须通过 GET 请求完成。JSONP 解决方案不使用 XmlHttpRequest 对象,因此它不是标准理解方式中的 AJAX 请求,但内容仍然是动态访问的 - 对最终用户没有区别。
$.ajax({
url: url,
type: "GET"
dataType: "jsonp",
...
Second, you provide data incorrectly. You're pushing javascript object (created using object literals) onto the wire instead of its serialized JSON representation. Create JSON string (not manually, use e.g. JSON.stringify
converter):
其次,您提供的数据不正确。您将 javascript 对象(使用对象文字创建)推送到网络上,而不是其序列化的 JSON 表示。创建 JSON 字符串(不是手动,使用例如JSON.stringify
转换器):
$.ajax({
...
data: JSON.stringify({u: userid, p: pass}),
...
Last issue, you've set async
to false
, while documentation says:
最后一期,您已设置async
为false
,而文档说:
Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.
跨域请求和 dataType: "jsonp" 请求不支持同步操作。
回答by Mikeldi
I've been struggling like you for a while trying to handle errors on ajax jsonp DataType requests, however I want to share you my code, hope it helps. A basic thing is to include a timeout on the ajax request, otherwise it'll never enter the error: function
我和你一样一直在努力处理 ajax jsonp DataType 请求上的错误,但是我想和你分享我的代码,希望它有所帮助。一个基本的事情是在ajax请求中包含超时,否则它永远不会输入错误:函数
$.ajax({
url: "google.com/api/doesnotexists",
dataType: "jsonp",
timeout: 5000,
success: function (parsed_json) {
console.log(parsed_json);
},
error: function (parsedjson, textStatus, errorThrown) {
console.log("parsedJson: " + JSON.stringify(parsedjson));
$('body').append(
"parsedJson status: " + parsedjson.status + '</br>' +
"errorStatus: " + textStatus + '</br>' +
"errorThrown: " + errorThrown);
}
});
jsfiddle - Handle Errors with jquery ajax call and JSONP dataType - Error 404
回答by Brian
I'm building a fragile JS project that uses jquery-jsonp, and came up with a dual-jsonp/ajax approach that handles errors no matter which method ends up being used.
我正在构建一个使用 jquery-jsonp 的脆弱 JS 项目,并提出了一种双 jsonp/ajax 方法,无论最终使用哪种方法,它都会处理错误。
function authenticate(user, pass) {
var ajax = ($.jsonp || $.ajax)({
'url': /* your auth url */,
'data': { /* user, pass, ... */ },
'contentType': "application/javascript",
'dataType': 'jsonp',
'callbackParameter': 'callback' // $.jsonp only; $.ajax uses 'jsonpCallback'
});
ajax.done(function (data) {
// your success events
});
ajax.fail(function (jqXHR, textStatus, errorThrown) {
// $.jsonp calls this func as function (jqXHR, textStatus)
// and $.ajax calls this func with the given signature
console.error('AJAX / JSONP ' + textStatus + ': ' +
(errorThrown || jqXHR.url));
});
}
Since both jquery-jsonp and $.ajax support the jQuery Deferred specification, we can merge the two error handlers together, handling 400 and 500-series errors, as well as lookup timeouts.
由于 jquery-jsonp 和 $.ajax 都支持 jQuery Deferred 规范,我们可以将两个错误处理程序合并在一起,处理 400 和 500 系列错误,以及查找超时。
回答by Markus
Old question but I had the same problem. Here is a solution that worked for me.
老问题,但我有同样的问题。这是一个对我有用的解决方案。
If you ownthe domain you shoot your request at, you can set a variable in the response and check for it on the client side.
如果您拥有发出请求的域,您可以在响应中设置一个变量并在客户端检查它。
Server Side:
服务器端:
SERVER_RESPONSE=true; Callback(parameter1, parameter2);
Client Side:
客户端:
if(typeof SERVER_RESPONSE === 'undefined'){
console.log('No Response, maybe server is down');
}
else{
console.log('Got a server response');
}