Jquery ajax自定义错误处理程序



我正在JSON服务器上编写一个骨干js web应用程序,该服务器以JSend规范格式返回JSON响应。

下面是这种格式的几个例子:

<<p> GET/文章/strong>
{
 "status": "success",
 "data": {
   "posts" [
     {"id": 1, "title": "A blog post"}, 
     {"id": 2, "title": "another blog post"}
   ]
 }
}

POST/帖子

{
  "status": "fail",
  "data": {
    "title": "required"
  }
}

默认情况下,"error"事件在$。ajax由http代码触发,但由于JSend规范格式根本不使用http代码,因此我必须重写$。Ajax错误处理程序。

默认的工作方式(http代码):

$.ajax({
  error: function() {
    // Do your job here.
  },
  success: function() {
    // Do your job here.
  }
});

如何重写$。Ajax错误处理程序,它得到触发时,解析的身体,如果"状态"属性是"失败"或"错误"?

这似乎是违反直觉的,您必须将其放在success函数中。只需自己检查值:

$.ajax({
  error: function() {
    // Handle http codes here
  },
  success: function(data) {
    if(data.status == "fail"){
      // Handle failure here
    } else {
      // success, do your thing
    }
  }
});

要保持DRY,您可以使用以下命令:

function JSendHandler(success, fail) {
    if (typeof success !== 'function' || typeof fail !== 'function') {
        throw 'Please, provide valid handlers!';
    }
    this.success = success;
    this.fail = fail;
}
JSendHandler.prototype.getHandler = function () {
    return function (result) {
        if (result.status === 'fail') {
            this.fail.call(this, arguments);
        } else {
            this.success.call(this, arguments);
        }
    }
};
function success() { console.log('Success'); }
function error() { console.log('Fail!'); }
var handler = new JSendHandler(success, error);
$.ajax({
  error: error,
  success: handler.getHandler()
});

最新更新