最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery. $.post request .done() .fail() avoid code duplication - Stack Overflow

programmeradmin0浏览0评论

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') ??

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') ??

Share Improve this question asked Dec 20, 2012 at 9:51 Igor SlipkoIgor Slipko 1051 gold badge1 silver badge5 bronze badges 1
  • If the server is yours, why not just send a different HTTP header on error? – John Dvorak Commented Dec 20, 2012 at 9:57
Add a comment  | 

4 Answers 4

Reset to default 8

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.

$.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, e.g.

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:

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

...

.done(function(){
   //xxx
}).fail(function(){
   //yyy
});
发布评论

评论列表(0)

  1. 暂无评论