Javascript Jquery 获取有关 XHR 错误的数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3978634/
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
Jquery get data on XHR error
提问by James Moore
If I make a jquery AJAX request which is succesful I get back my JSON data. However, If I make a request and I get somthing other than a 200 response code back, I cannot get back the data in the Jquery call back. I need the data as it has a description about the data.
如果我发出成功的 jquery AJAX 请求,我将取回我的 JSON 数据。但是,如果我发出请求并且收到 200 响应代码以外的其他内容,则无法取回 Jquery 回调中的数据。我需要数据,因为它有关于数据的描述。
success: function (data, tst, xhr) {
$.log('XHR OK');
},
error: function (xhr, tst, err) {
$.log('XHR ERROR ' + XMLHttpRequest.status);
},
Any ideas?
有任何想法吗?
Thanks
谢谢
回答by James Moore
In the:
在里面:
error: function (xhr, tst, err) {
$.log('XHR ERROR ' + XMLHttpRequest.status);
},
you can use
您可以使用
error: function (XMLHttpRequest, textStatus, errorThrown) {
$.log('XHR ERROR ' + XMLHttpRequest.status);
return JSON.parse(XMLHttpRequest.responseText);
},
to get the JSON response in in event of an error.
在发生错误时获取 JSON 响应。
XMLHttpRequest.responseText
Cheers.
干杯。
回答by betamax
Try the jQuery JSONP plugin. It adds an error callback to a JSON request like so:
试试jQuery JSONP 插件。它向 JSON 请求添加了一个错误回调,如下所示:
$.jsonp({
url: "Your URL",
data: {data: "Some Data"},
dataType: 'jsonp',
timeout: 2000,
success: function(data, status) {
// Do something with data here
},
error: function(xhr, text_status){
// Handle the server error
}
});
It does this using a timeout to wait for the server. Unfortunately, there is no other way of telling if the server response with something other than a 200 response.
它使用超时来等待服务器来做到这一点。不幸的是,没有其他方法可以判断服务器是否使用 200 以外的响应进行响应。