jQuery ajax自定义错误处理程序 [英] jquery ajax custom error handler
问题描述
我正在JSON服务器上编写一个主干js Web应用程序,该应用程序以J 发送规范返回JSON响应.格式.
I am writing an backbone js web app on top of an JSON server that returns JSON responses in JSend specification format.
以下是该格式的一些示例:
Here are a few examples of that format:
获取/帖子
{
"status": "success",
"data": {
"posts" [
{"id": 1, "title": "A blog post"},
{"id": 2, "title": "another blog post"}
]
}
}
POST/帖子
{
"status": "fail",
"data": {
"title": "required"
}
}
默认情况下,$.ajax中的错误"事件由http代码触发,但是由于JSend规范格式根本不使用HTTP代码,因此我必须重写$ .ajax错误处理程序.
By default the "error" event in $.ajax gets triggered by http codes, but since the JSend specification format does not use HTTP codes at all, I have to rewrite the $.ajax error handler.
默认情况下的工作方式(http代码):
The way it works by default (http codes):
$.ajax({
error: function() {
// Do your job here.
},
success: function() {
// Do your job here.
}
});
我如何重写在解析正文时以及状态"属性是失败"还是错误"时触发的$ .ajax错误处理程序?
How can I rewrite the $.ajax error handler that it gets triggered when parsed the body and if the "status" property is "fail" or "error"?
推荐答案
看起来似乎违反直觉,您必须将其放在success
函数中.只需自己检查一下值:
As counter-intuitive as it seems, you will have to put it in the success
function. Simply check the value yourself:
$.ajax({
error: function() {
// Handle http codes here
},
success: function(data) {
if(data.status == "fail"){
// Handle failure here
} else {
// success, do your thing
}
}
});
这篇关于jQuery ajax自定义错误处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!