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

I have a mail 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 mail request if the code in the .done () method (comment "yyy") is the same in the fail method (comment "yyy")?

+4
source share
4 answers

You can always use the callback method, and the request will always be in this block. As you know, when the data contains an error and not, this method will work for server-side errors. And you can catch errors on the client side by specifying the last 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 } }); 
+3
source

The most obvious and simplest solution would be to simply execute a failure callback as follows:

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

Ask them to call the same function, for example

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

An alternative would be to slightly modify the protocol and use HTTP status codes to indicate success or failure:

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

...

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

All Articles