jQuery 你如何处理来自 AJAX 调用的错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/407596/
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
How do you handle errors from AJAX calls?
提问by Kevin Pang
Let's say I have the following jQuery AJAX call:
假设我有以下 jQuery AJAX 调用:
$.ajax({
type: "POST",
url: "MyUrl",
data: "val1=test",
success: function(result){
// Do stuff
}
});
Now, when this AJAX call is made I want the server-side code to run through a few error handling checks (e.g. is the user still logged in, do they have permission to use this call, is the data valid, etc). If an error is detected, how do I bubble that error message back up to the client side?
现在,当进行这个 AJAX 调用时,我希望服务器端代码运行一些错误处理检查(例如,用户是否仍然登录,他们是否有权使用这个调用,数据是否有效等)。如果检测到错误,我如何将该错误消息冒泡回客户端?
My initial thought would be to return a JSON object with two fields: error and errorMessage. These fields would then be checked in the jQuery AJAX call:
我最初的想法是返回一个带有两个字段的 JSON 对象:error 和 errorMessage。然后将在 jQuery AJAX 调用中检查这些字段:
$.ajax({
type: "POST",
url: "MyUrl",
data: "val1=test",
success: function(result){
if (result.error == "true")
{
alert("An error occurred: " & result.errorMessage);
}
else
{
// Do stuff
}
}
});
This feels a bit clunky to me, but it works. Is there a better alternative?
这对我来说有点笨拙,但它有效。有更好的选择吗?
回答by Asciant
Personally, I have similar code to the following code in my library.
就个人而言,我的库中有与以下代码类似的代码。
$.ajaxSetup({
error: function(xhr){
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
}
});
jQuery docs Ajax/jQuery.ajaxSetup
jQuery 文档 Ajax/jQuery.ajaxSetup
The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function. This also means that you do not have to define an error: call in every $.ajax call.
将错误从服务器端(使用 php)冒泡到客户端的最好方法是通过 Ajax 请求在 400 的某个地方发送一个标头(这总是与错误相关联)。一旦 Ajax 请求收到它,它就会触发你的错误函数。这也意味着您不必定义错误:在每个 $.ajax 调用中调用。
header('HTTP/1.0 419 Custom Error');
Quote from w3.org header information
Error 4xx, 5xx The 4xx codes are intended for cases in which the client seems to have erred, and the 5xx codes for the cases in which the server is aware that the server has erred. It is impossible to distinguish these cases in general, so the difference is only informational. The body section may contain a document describing the error in human readable form. The document is in MIME format, and may only be in text/plain, text/html or one for the formats specified as acceptable in the request.
错误 4xx、5xx 4xx 代码用于客户端似乎出错的情况,5xx 代码用于服务器知道服务器出错的情况。一般无法区分这些情况,因此差异仅是信息性的。正文部分可能包含以人类可读形式描述错误的文档。该文档采用 MIME 格式,并且只能采用 text/plain、text/html 或请求中指定为可接受的格式之一。
回答by Salty
$.ajax({
type: "POST",
url: "MyUrl",
data: "val1=test",
success: function(result){
// Do stuff
},
error: function(request,status,errorThrown) {
// There's been an error, do something with it!
// Only use status and errorThrown.
// Chances are request will not have anything in it.
}
});
回答by rodbv
Doesn't the jQuery ajax function accept one more parameter at the end, a callback for failed calls? If so, just add a fail:function(...){..}
after the success callback.
jQuery ajax 函数最后不是再接受一个参数,即失败调用的回调吗?如果是这样,只需fail:function(...){..}
在成功回调后添加一个。
回答by Adam Peck
Return an error code on the server side using the HTTP error the best equates to what the error is. Then use the error callback. This will also allow you to show errors given by your webserver.
使用 HTTP 错误在服务器端返回错误代码,最能代表错误是什么。然后使用错误回调。这也将允许您显示您的网络服务器给出的错误。
回答by WitVault
It's pretty late to answer this question but I think It will be beneficial to some one using es6 and jquery 2.2.
回答这个问题已经很晚了,但我认为这对使用 es6 和 jquery 2.2 的人会有所帮助。
I generally follow this (deferred approach) in my code
我通常在我的代码中遵循这个(延迟方法)
sendAjaxRequest(URL, dataToSend) {
return $.ajax({
type : 'POST',
url : URL,
data : JSON.stringify(dataToSend),
dataType : 'json'
}).fail((responseData) => {
if (responseData.responseCode) {
console.error(responseData.responseCode);
}
});
},
I have attached a deferred fail
method which will be called if some error occurs. It is an alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method in latest jquery.
我附上了一个延迟fail
方法,如果发生某些错误,它将被调用。它是错误回调选项的替代构造,.fail() 方法替换了最新 jquery 中已弃用的 .error() 方法。
Next from the place of calling sendAjaxRequest
I use then
jquery promise callback
接下来从调用的地方sendAjaxRequest
我使用then
jquery承诺回调
sendAjaxRequest(URL, dataToSend)
.then(
(success) => {
},
(error) => {
}
);
It will call success or error function based on the response received from server.
它将根据从服务器收到的响应调用成功或错误函数。