javascript 查询。$.post request .done() .fail() 避免代码重复

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13969345/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:20:48  来源:igfitidea点击:

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

javascriptjquery-uijqueryjquery-plugins

提问by Igor Slipko

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')中的代码与失败方法(注释 'yyy')中的代码相同,如何避免 post 请求中的代码重复??

采纳答案by halilb

You can use alwayscallback 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
    }
});

回答by Rudi Visser

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);

回答by Jensen Ching

Have them call the same function, e.g.

让他们调用相同的函数,例如

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

回答by John Dvorak

An alternative would be to change the protocol slightly, and make use of the HTTP status codesto indicate success or failure:

另一种方法是稍微更改协议,并使用HTTP 状态代码来指示成功或失败:

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

...

...

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