Ajax again Encapsulation! __ Natural Architecture

Source: Internet
Author: User

jquery Ajax is already very convenient, why in the further encapsulation of it. This first depends on the specific requirements of the project, and if you don't think you need it, then you can simply use the various Ajax methods provided by jquery directly. If, like me, it is not very convenient, then completely can according to their own ideas and needs to be packaged again.

  Requirements:

1, the time to call more simple.

2, can be flexible to do a variety of settings and changes.

3, can meet a number of general needs. For example, give a hint when you make a mistake.

  Project Status:

Ajax request, there will be a loaded animation, in the Ajax launch to automatically start, after loading to automatically stop. An error is also stopped automatically, and an error message is given. The URL of the request is more fixed, according to the deletion to check to classify. You can cross a domain or not across a domain. Need to be flexible to switch. While Ajax gets the data, it also comes with a piece of debugging information that needs to be displayed. There are specialized handler functions, but they need to be invoked.

  implementation:

Go directly to the code.

Encapsulation of Ajax Nature.ajax = function (Ajax) {//most basic layer encapsulation//define default value var Defaultinfo = {type
            : "Get",//Access mode: If Datapata is not empty, it is automatically set to post, or if NULL is set to get. DataType:Nature.sendDataType,//data type: JSON, JSONP, text. By configuration information to handle, easy to set cache:true,//whether cache, default cache xhrfields: {//Allow Cross Add cookies when domain access. When Cors Cross-domain, you need to set Withcredentials:true}, Urlpata: {},//url parameters after.
            Will be added to the URL and will not be added to the form. Formpata: {},//The parameters in the form.

            If datatype is JSON, it must be added to the form, not appended to the URL, and if datatype is JSONP, it can only be appended to the URL. URL://Depending on the top specified//timeout:2000, error:function () {},/////If there is an error, stop loading the animation and give a hint. You can also add your own handler success:function () {}////Success to display debug information.

        You can also add your own handler};
        Complement Ajaxinfo if (typeof ajaxinfo.datatype = = "undefined") {ajaxinfo.datatype = Defaultinfo.datatype;
    }    
        if (typeof ajaxinfo.formpata = = "undefined") {Ajaxinfo.type = "get";
            else {if (Ajaxinfo.datatype = = "JSON") {Ajaxinfo.type = "POST";
            else {//get or Jsonp Ajaxinfo.type = "POST";

        } ajaxinfo.data = Ajaxinfo.formpata;
        } if (typeof Ajaxinfo.cache = = "undefined") {Ajaxinfo.cache = Defaultinfo.cache;
            }//Process URL if (typeof ajaxinfo.urlpata!= "undefined") {var Tmpurlpara = "";
            var para = Ajaxinfo.urlpata;
            for (var key in para) {Tmpurlpara + = "&" + key + "=" + Para[key]; if (ajaxInfo.url.indexOf ('? ') >= 0) {//original address has parameters, directly add Ajaxinfo.url + + Tmpur
            Lpara;
            else {//The original address has no parameters, become? Add Ajaxinfo.url + + tmpurlpara.replace (' & ', '? ');

       }
        } Start executing ajax $.ajax ({type:ajaxInfo.type, dataType:ajaxInfo.dataType, cache:
            Ajaxinfo.cache, Xhrfields: {//Allow adding cookies when cross domain access withcredentials:true }, Url:ajaxInfo.url, Data:ajaxInfo.data,//timeout:2000, Error:fu Nction () {//access failed, auto load animation stopped, and an error occurred while prompting alert ("Submit" + Ajaxinfo.title +).
                ");
                if (typeof top.spinstop!= "undefined") top.spinstop ();
            if (typeof ajaxinfo.error = = "function") ajaxinfo.error (); }, Success:function (data) {if (typeof) (parent. Debugset)!= "undefined") parent.  Debugset (Data.debug);
                
                Invokes a function that displays debugging information.
                if (typeof (ajaxinfo.ctrlid) = = "undefined") ajaxinfo.success (data); else {ajaxinfo.success (ajaxinfo.ctrLId, data);
    

   

}

            }
        }); };

This is the bottom of the package, and then the package based on the URL, in fact, is to avoid the code to write around the problem of URLs.

 1 Nature.Data.MetaData = function () {2 3 var ajax = nature.ajax;//Simplify 4 5 6/* Get the metadata for Page view * * 7 this         . Ajaxgetmeta = function (ajaxdata) {8 9 Ajaxdata.url = Nature.resourceurl + "/metadata/getmeta.ashx"; 10
Ajaxdata.cache = false;
One Ajax (Ajaxdata);
13}; Nature.Data.CusData = function () {var ajax = Nature.ajax 22 23 34//Received Take customer Data This.ajaxgetdata = function (ajaxdata) {36 37///delete the URL of the search service URL = Nature.resourceurl 3
9 if (typeof Ajaxdata.url = = "undefined") URL + "/data/getdata.ashx";
/else the URL + ajaxdata.url;
Ajaxdata.url = URL;
Ajaxdata.cache = false;
The Ajax (Ajaxdata);
48 49};         
50 51/* Delete Data * * This.ajaxdeletedata = function (ajaxdata) {var url = Nature.resourceurl 54 if (typeof Ajaxdata.url = = "Undefined ") at the URL +"/data/getdata.ashx ";
else is the URL = ajaxdata.url;
Ajaxdata.url = URL;
Ajaxdata.cache = false;
The Ajax (Ajaxdata);
64}; 65 66 67}

This is according to add and delete to check the URL address to set several functions. The main purpose is to deal with the specific URL, to avoid the code inside the confusion of the URL is everywhere.

Finally, the specific application of the place.

1  var load = new Nature.Data.MetaDate ();
 2 
 3   load.ajaxgetmeta ({
 4             urlpata: {action: "Tree", mdid:0, Dbid:databaseid, Projectid:projectid, cachekey:0},
 5             title: "Get XXX",
 6             success:function (msg) {
 7                 
 8                 if (typeof Top.__cache = = "undefined")
 9                     Top.__cache = {};/* to open cache space * *                 top.__cache.treemeta = msg.data;                 Create2 (msg.data);
}         );

This is simpler to call, avoiding some common and fixed parameter settings, such as type, DataType, cache, URL, and so on. May be some children's shoes will think, not have $.get and $.post, more concise than you, you also toss what.

$.get and $.post are really more concise, but not flexible, such as cache settings, sometimes need to cache, and sometimes do not need caching. Another example is type, where some pages need to be cross-domain, and some do not need to cross domains. There are times when you want to unify the settings (toggle) According to the project. So I had a little bit of a toss.

  Detailed Description:

The meaning of several properties in the default argument.

1, title. Ajax may be wrong, there should be a hint of error. But a page often has more than one Ajax, which is exactly what went wrong. So I set a title attribute, and when the error alert ("Submit" + Ajaxinfo.title +), there are errors. ); This is clearer, at least according to the title of the attribute value to find, you can quickly locate.

2, Urlpata and Formpata. jquery Ajax has only one attribute of data. When get, will put data into the URL, passed to the server, when the post, will put data in the form, submitted to the server. This seems pretty good, but when I post, I need to explicitly put some parameters in the URL, some parameters in the form. This can not be all in the data inside, I have to splice the URL myself. Trouble still love mistakes. So I split it into two attributes Urlpata and Formpata.

Urlpata will certainly appear in the URL. Formpata will need to be based on the situation. JSON will be placed in the form, JSONP can only be placed in the URL.

3, Xhrfields. This involves HTML5.0 support for post Cross-domain. Generally referred to Cross-domain, think of is JSONP, but Jsonp is disguised as <script> to achieve the Cross-domain, because JS does not support

Related Article

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.