Using the overridden $.ajax () Unified error Handling

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.