简体   繁体   English

JQuery的。 $ .post请求.done()。fail()避免代码重复

[英]JQuery. $.post request .done() .fail() avoid code duplication

I have a post request like 我有一个帖子请求

  $.post("test", {
    ajax: "true",
    action: ""
  }).done(function(data){
    if (data == "ok"){
        //xxx
    } else if (data == "err"){
        //yyy
    }
  }).fail(function(){
    //yyy
  });

How to avoid code duplication in the post request if code in .done() method (comment 'yyy') the same in fail method (comment 'yyy') ?? 如果.done()方法中的代码(注释'yyy')在fail方法中相同(注释'yyy'),如何避免post请求中的代码重复?

The most obvious and simple solution would be to simply have a failure callback like so: 最明显和最简单的解决方案是简单地进行故障回调,如下所示:

function ajaxFailed() {
    // yyy
}

$.post("test", {
    ajax: "true",
    action: ""
}).done(function(data){
    if (data == "ok"){
        //xxx
    } else if (data == "err"){
        ajaxFailed();
    }
}).fail(ajaxFailed);

You can use always callback method, and the request will always go in that block. 您可以使用始终回调方法,并且请求将始终进入该块。 As you know when data contains error and not, this method will work for server-side errors. 如您所知,当数据包含错误时,此方法将适用于服务器端错误。 And you can catch client-side errors by defining the final else block. 您可以通过定义最终的else块来捕获客户端错误。

$.post("test", {
    ajax: "true",
    action: ""
}).always(function(data){
    if (data == "ok"){
        //xxx
    } else if (data == "err"){
        //handle server-side errors
    } else {
        //handle client-side errors like 404 errors
    }
});

Have them call the same function, eg 让他们调用相同的功能,例如

function onErr() { 
    //yyy
}
$.post("test", {
    ajax: "true",
    action: ""
}).done(function(data){
    if (data == "ok"){
        //xxx
    } else if (data == "err"){
        onErr();
    }
}).fail(onErr);

An alternative would be to change the protocol slightly, and make use of the HTTP status codes to indicate success or failure: 另一种方法是稍微更改协议,并使用HTTP状态代码来指示成功或失败:

if($sqlError){
  header("HTTP/1.1 503 Service unavailable");
}

... ...

.done(function(){
   //xxx
}).fail(function(){
   //yyy
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM