Javascript 如何根据服务器响应而不是 HTTP 500 触发 jquery.ajax() 错误回调?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6265814/
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 to trigger jquery.ajax() error callback based on server response, not HTTP 500?
提问by Leem
By using jquery ajax function, I can do something like:
通过使用 jquery ajax 函数,我可以执行以下操作:
$.ajax({
url: url,
type: 'GET',
async: true,
dataType: 'json',
data: data,
success: function(data) {
//Handle server response here
},
error: function(xhr, status, error){
//Handle failure here
}
});
I got two questions to ask based on above code:
根据上面的代码,我有两个问题要问:
When will the jquery.ajax()
error
callback be called??What if server response to me a json object with string message "There is an error". Which means the request is still send successfully, but I got server response
{message: "There is an error"}
.
什么时候会
error
调用jquery.ajax()回调??如果服务器向我响应一个带有字符串消息“存在错误”的 json 对象怎么办。这意味着请求仍然发送成功,但我得到了服务器响应
{message: "There is an error"}
。
I think no matter what string value server is responsed, if client got server's response, the jquery.ajax()success
callback will be triggered anyway.
我认为无论服务器响应什么字符串值,如果客户端得到服务器的响应,无论如何都会触发jquery.ajax()success
回调。
I'd like to ask if server specifically returns to me a JSON object with string value like {message: 'There is an error'}
, could server do something so that this response could be handled in jquery.ajax()error
callback instead of success
callback?
我想问一下服务器是否专门返回给我一个带有字符串值的 JSON 对象,如{message: 'There is an error'}
,服务器可以做些什么以便可以在jquery.ajax()error
回调而不是success
回调中处理这个响应?
采纳答案by RaYell
The error callback will be executed when the response from the server is not going to be what you were expecting. So for example in this situations it:
当来自服务器的响应不是您所期望的时,将执行错误回调。因此,例如在这种情况下:
- HTTP 404/500 or any other HTTP error message has been received
- data of incorrect type was received (i.e. you have expected JSON, you have received something else).
- 已收到 HTTP 404/500 或任何其他 HTTP 错误消息
- 收到了不正确类型的数据(即,您希望收到 JSON,但收到了其他内容)。
In your situation the data is correct (it's a JSON message). If you want to manually trigger the error callback based on the value of the received data you can do so quite simple. Just change the anonymous callback for error to named function.
在您的情况下,数据是正确的(它是 JSON 消息)。如果你想根据接收到的数据的值手动触发错误回调,你可以很简单地做到这一点。只需将错误的匿名回调更改为命名函数即可。
function handleError(xhr, status, error){
//Handle failure here
}
$.ajax({
url: url,
type: 'GET',
async: true,
dataType: 'json',
data: data,
success: function(data) {
if (whatever) {
handleError(xhr, status, ''); // manually trigger callback
}
//Handle server response here
},
error: handleError
});
回答by Simen Brekken
We presume the server is sending JSON, and in case of a successful request we'll get something like this:
我们假设服务器正在发送 JSON,如果请求成功,我们将得到如下信息:
{
success: true,
data: {
name: 'Foo'
}
}
... and on failure:
......失败时:
{
success: false,
error: 'Something bad happened.'
}
Then we simply filter the response with a $.Deferred:
然后我们简单地用$.Deferred过滤响应:
$.get('http://localhost/api').then(function(res) {
var filter = $.Deferred();
if (res.success) {
filter.resolve(res.data);
} else {
filter.reject(res.error);
}
return filter.promise();
}).done(function(data) {
console.log('Name:', data.name); // Outputs: Foo
}).fail(function(error) {
console.log('Error:', error); // Outputs: Something bad happened.
})
回答by Fosco
The error callback is for when the Ajax round-trip could not be completed successfully, not something based on your server logic. It would be your responsibility to check for what you consider to be a successful response inside the success callback. i.e. Add a single IF conditional that checks if the message = "There was an error." and include your error logic there, otherwise do the success logic.
错误回调是针对 Ajax 往返无法成功完成的,而不是基于您的服务器逻辑的。您有责任在成功回调中检查您认为是成功的响应。即添加一个 IF 条件来检查消息是否 =“发生错误”。并在那里包含您的错误逻辑,否则执行成功逻辑。
An approach to do what you ask for would be to have the server return a 404 header when there is an error, then it would be handled by the error callback. The problem with this approach is that you'd be hiding if there are actual errors, and you wouldn't be able to pass additional data with it.
执行您要求的一种方法是让服务器在出现错误时返回 404 标头,然后由错误回调处理。这种方法的问题在于,如果存在实际错误,您将隐藏起来,并且您将无法通过它传递其他数据。
回答by Gary Green
Simplest thing to do would be to restructure like so:
最简单的方法是像这样重组:
function handleAjaxError function(xhr, status, error) {
//Handle failure here
}
$.ajax({
url: url,
type: 'GET',
async: true,
dataType: 'json',
data: data,
success: function(data) {
//Handle server response here
if (data.message == 'There is an error')
{
handleAjaxError();
return;
}
//... all is good....
},
error: handleAjaxError
});
回答by dallin
One easy way to do this is to just use the jQuery always() function for your callback and then if you want to manually create an error just take advantage of Duck Typing!
一种简单的方法是仅使用 jQuery always() 函数进行回调,然后如果您想手动创建错误,只需利用 Duck Typing!
For example:
例如:
$.get(url, {"data": data}).always(function(result)
{
if (typeof result.status !== "undefined" && result.status !== 200) // Status code 200 represents Success/OK
{
//handle error
error = "Your error was " + result.status + " " + result.statusText;
}
else
{
//success
}
});
The error section will always be run if there was a natural header error such as a 404 Not Found. If you want to manually return an error, you can just emulate the XHR object normally passed with an error (e.g. in PHP):
如果存在自然的标头错误(例如 404 Not Found),则错误部分将始终运行。如果您想手动返回错误,您可以模拟通常带有错误的 XHR 对象(例如在 PHP 中):
public function ServerSideAjaxResponse($data)
{
if (!$data)
{
$response["status"] = 1001; //Make up your own error codes! Yippee! Fun!
$response["statusText"] = "Error! You forgot to send the data!";
echo json_encode($return);
return;
}
}
回答by Ben in CA
This original question was posted years ago, and perhaps there are better ways of handling this now. Here's a suggestion to handle multiple types of errors, including the OP's question.
这个最初的问题是几年前发布的,现在也许有更好的方法来处理这个问题。这是处理多种类型错误的建议,包括 OP 的问题。
Input type (error) example #1
输入类型(错误)示例 #1
function handleError (type){
type = type || "Connection Issue";
var value = "Error occurred: " + type;
alert(value);
}
function checkIfError(response){
if (response == "DB_ERROR") {
handleError("Server error");
throw new Error("JS died"); // optional, keep from running additional script
}
}
var example = {
success: function (response) {
checkIfError(response); // check data if error msg
// do stuff when proper data sent
alert(response);
}, error: handleError // connection error, call error msg
};
test1 = example['error']();
Input type (success:error) example #2
输入类型(成功:错误)示例 #2
function handleError (type){
type = type || "Connection Issue";
var value = "Error occurred: " + type;
alert(value);
}
function checkIfError(response){
if (response == "DB_ERROR") {
handleError("Server error");
throw new Error("JS died"); // optional, keep from running additional script
}
}
var example = {
success: function (response) {
checkIfError(response); // check data if error msg
// do stuff when proper data sent
alert(response);
}, error: handleError // connection error, call error msg
};
test2 = example['success']("DB_ERROR");
Input type (success) example #3
输入类型(成功)示例 #3
function handleError (type){
type = type || "Connection Issue";
var value = "Error occurred: " + type;
alert(value);
}
function checkIfError(response){
if (response == "DB_ERROR") {
handleError("Server error");
throw new Error("JS died"); // optional, keep from running additional script
}
}
var example = {
success: function (response) {
checkIfError(response); // check data if error msg
// do stuff when proper data sent
alert(response);
}, error: handleError // connection error, call error msg
};
test3 = example['success']("Proper Response");
By using functions, if you have multiple calls in your scripts, you can simplify changes.
通过使用函数,如果您的脚本中有多个调用,您可以简化更改。
Have your PHP (or whatever server side code) return the response of "DB_ERROR"(or whatever you want) to trigger the error; allows you to do different things depending on the error.
让您的 PHP(或任何服务器端代码)返回“DB_ERROR”(或任何您想要的)响应以触发错误;允许您根据错误做不同的事情。