In jquery development, we often use code similar to the following:
$.ajax({ ‘...‘, ‘POST‘, data : {}, function(data){ //执行状态是200时候调用 }, function(XMLHttpRequest, msg, e){ //执行状态是非200时调用 }, function(httpRequest, status){ //完成了一次请求时调用 } });
In fact, in addition to Url,data,success, the other code is repeated
At this point we can use our own rewritten Ajax functions to circumvent these duplicate codes:
( function($){ //Back up a primitive Jquery.ajax () function First var_ajax = $.ajax;//override Jquery.ajax () function$.ajax = function(options){Options.type =' POST '; Options.error = function(XMLHttpRequest, MSG, E){ //Unified error Handling}, Complete: function(HttpRequest, status){ //Unified End Status Display //Can be combined with a GIF to make progress display}}) (JQuery);
With the above definition, we call only when we need to:
$.ajax({ ‘...‘, data : {}, function(data){ //只需在此处理正常情况 }});
This way we can handle the error uniformly , or we can do a ' loading ... ' dynamic display in complete.
Tells the user that we are in the background processing, also can prevent the user to repeatedly click (about ' Loading ... ' code, can refer to next article).
Copyright NOTICE: This article is the original blogger article, please indicate the source when reproduced.
Using the overridden $.ajax () Unified error Handling