Overriding the $.ajax method

Source: Internet
Author: User

1 /*rewrite the Ajax wrapper shell in jquery*/2$(function () {3(function ($) {4         //first back up the AJAX approach to jquery5         var_ajax =$.ajax;6 7         //the Ajax method of rewriting jquery8$.ajax =function(opt) {9             //back up the error and success methods in OPTTen             varfn = { OneBeforesend:function(XHR) {}, AErrorfunction(XMLHttpRequest, Textstatus, Errorthrown) {}, -Successfunction(data, textstatus) {}, -Completefunction(XHR, TS) {} the             } -  -             if(opt.beforesend) { -Fn.beforesend =Opt.beforesend; +             } -             if(opt.error) { +Fn.error =Opt.error; A             } at             if(opt.success) { -Fn.success =opt.success; -             } -             if(opt.complete) { -Fn.complete =Opt.complete; -             } in  -  to  +             //Extended Enhancement Processing -             var_opt =$.extend (opt, { the                 //Global allow cross-domain * xhrfields: { $Withcredentials:truePanax Notoginseng                 }, -Errorfunction(XMLHttpRequest, Textstatus, Errorthrown) { the                     //Error method Enhancement processing + Fn.error (XMLHttpRequest, Textstatus, errorthrown); A                 }, theSuccessfunction(data, textstatus) { +                     //successful callback method enhancement processing - fn.success (data, textstatus); $                 }, $Beforesend:function(XHR) { -                     //Pre-Commit callback method - fn.beforesend (XHR); the                 }, -Completefunction(XHR, TS) {Wuyi                     //The callback function after the request is completed (called after the request succeeds or fails).  the Fn.complete (XHR, TS); -                 } Wu             }); -             if(opt.xhrfields) { About_opt.xhrfields =Opt.xhrfields; $             } -  -             //calling the native Ajax method -             return_ajax (_opt); A         }; + }) (jQuery); the});

jquery rewrite (extension) $.ajax and $.fn.load and other methods to do things today, consider the user's best experience, to achieve the interface on the asynchronous request data loading effect, the function code is written by others, about dozens of places, with the jquery load method. The whole ah, always can not go to each method inside add effect bar, dozens of places.         Reasoning, can only use rewrite, do not say, open dry. As a senior small white, has never rewritten the method of jquery, relying on the degree Niang, plus looked at the source of jquery, and finally solved the problem. So with this blog post, to small sum of knowledge or help "Freemasonry" people, some resources from the network, if there are flaws, but also hope Haihan and pointed out.

First, the prerequisite knowledge

Before you page down, it is necessary to know the following:

1. (function ($) {...}) (JQuery)

The function ($) inside the first parenthesis {...} is actually an anonymous function whose formal parameter is $, which is very strange, but it is mainly to not conflict with other libraries. When we call a function, we usually have parentheses and arguments behind the function name, but because the operator's precedence we define the anonymous function to be enclosed (), so there is the preceding (function ($) {...}).

Now what does this code mean? You should be very clear: the first parenthesis indicates that an anonymous function is defined, and then (jquery) represents the arguments passed by the function, the whole meaning is to define an anonymous function, then call the function, and pass the argument jQuery, equivalent to-- function Fun ($) {...}; Fun (jQuery);

This method is mostly used for the development of plug-ins, when executing the code, the DOM object does not necessarily load complete. The opposite is $ (function () {}), which is used when the DOM object of the page is loaded. In fact, the full write of this method is: $ (document). Ready (function () {});

2.$.fn.extend and $.extend

jquery has two methods for developing plug-ins, namely:

JQuery.fn.extend (object);//Add a method for the instance object of jquery

Jquery.extend (object);//Extend for the jquery class itself, add new methods or overwrite the original method

(1) $.fn.extend

In jquery there are the following source code:

[JavaScript]View PlainCopy
    1. Jquery.fn = Jquery.prototype = {
    2. Init: Function (selector, context) {//....
    3.    //......
    4. };

This seems jquery.fn=jquery.prototype, but what is prototype?

In JavaScript, each function object has a default property of prototype, called the prototype member of the function object, which points to an object, called the prototype object of the function, and when each of us defines a function, JavaScript creates a corresponding prototype object. In other words, when we define a function, we actually get two objects, a function object, a prototype object.         The prototype object is a special object, and the prototype member of the function points to its prototype object, which can be referenced by the prototype member of the function object to get the prototype object. So FN represents the prototype object, and extend represents the extension, so $.fn.extend represents the extension method for the prototype object, and the method of extending this way can only be called with the object, example: [JavaScript]View PlainCopy
    1. $.fn.extend ({
    2. Test:function () {
    3. Alert ("test");
    4. }
    5. });
    6. $ ("#id"). Test ();

(2) $.extend

This means adding a class method for the jquery class (although jquery does not have the concept of class, but it seems a lot easier to understand the class), or simply to add a static method, and then you can call this extension method in other places directly, example:

[JavaScript]View PlainCopy
    1. $.extend ({
    2. Test:function (param) {
    3. alert (param);
    4. }
    5. });
    6. $.test (1); //The direct popup 1
3. JavaScript closure closure is JS is the difficulty is JS features, a lot of high-level applications are to rely on closures to achieve, a lot of network resources, here is not to repeat, it is best to understand the next. 4.JavaScript the Apply method and the Call method

These two concepts are also necessary to know, see my reproduced article: click here

Ii. overriding Method 1. Overriding the $.ajax method [JavaScript]View PlainCopy
  1. (function ($) {
  2. //First back up the Ajax method of jquery
  3. Var_ajax=$.ajax;
  4. //Rewrite the Ajax method of jquery
  5. $.ajax=function (opt) {
  6. //Backup the error and success methods in OPT
  7. var fn = {
  8. Error:function (XMLHttpRequest, textstatus, Errorthrown) {},
  9. Success:function (data, textstatus) {}
  10. }
  11. if (opt.error) {
  12. Fn.error=opt.error;
  13. }
  14. if (opt.success) {
  15. fn.success=opt.success;
  16. }
  17. //Extended enhancement processing
  18. var_opt = $.extend (opt,{
  19. Error:function (XMLHttpRequest, textstatus, Errorthrown) {
  20. //Error method enhancement processing
  21. Fn.error (XMLHttpRequest, Textstatus, Errorthrown);
  22. },
  23. Success:function (data, textstatus) {
  24. //Successful callback method enhanced processing
  25. Fn.success (data, textstatus);
  26. },
  27. Beforesend:function (XHR) {
  28. //Pre-commit callback method
  29. $ (' body '). Append ("<div id= ' ajaxinfo ' style= ' > is loading, please ...</div> later");
  30. },
  31. Complete:function (XHR, TS) {
  32. The callback function after the request is completed (called after the request succeeds or fails).
  33. $ ("#ajaxInfo"). remove ();;
  34. }
  35. });
  36. return _ajax (_opt);
  37. };
  38. }) (JQuery);
2. Overriding the $.load method [JavaScript]View PlainCopy
    1. //also first back up the load method of jquery under   
    2. VAR&NBSP;_LOAD=$.FN.LOAD;&NBSP;&NBSP;
    3. $.fn.extend ({  
    4.     load:function ( URL,PARAM,CALBCK) {  
    5.         < span class= "comment" >//other operations and processing   
    6.     //.   
    7.     //here the original load method is called with the Apply method, Because the Load method belongs to an object, it cannot be a direct object. _load (... )       
    8.     return  _load.apply (this,[url,param,calbck]);   
    9. &NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;
    10. })   

Overriding the $.ajax method

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.