The encapsulation of WEBAPI and OData based on jquery Ajax

Source: Internet
Author: User
Tags add json key modify query return domain access

The use of Webapi has brought a notable characteristic, which has certain requirements for type. The typical Ajax type is nothing more than two, get, and post. If you use Jsonp to cross a domain, you can only use get. But now that the WEBAPI is here, type has increased by more than one. Although this problem is not big, is a number of put, delete, see the request to master it. But I think, this always has to have a process, another write code when also think is put or post, in case of writing wrong, will bring unnecessary trouble. So can you encapsulate it?

The Ajax use of jquery is actually very simple, but still need to set a few parameters, then can be a little more concise? Or is it necessary to encapsulate it?

This is the problem of the beholder, in addition to see the environment, see demand. Simple requirements do not need to be packaged again, just use it. If the requirements are a bit more complex, it is also necessary to encapsulate them.

Let's take a look at the request first.

1, WEBAPI type is required.

2, OData has its own way of use and grammar format.

Looking at the target:

1, easy to use.

2, easy to change.

3, easy to replace.

Webapi just said, OData, indeed very powerful also very flexible, just too flexible, resulting in increased learning costs and time, then can also be encapsulated, become familiar with the way?

train of Thought

Someone may see this picture and think back: I k, need to be so complicated? Over-design it. In fact, this view of personal experience, experienced is very easy to understand, not experienced will be very strange. It seems strange to see the masterpiece of Brother Pei recently, why should it be so designed? In fact, I do not have that experience, perhaps later on understanding it.

Package Mode

Public Properties of the package, it depends on the actual requirements, such as my project needs to deal with the tenant ID, the head of the authorization processing (storage token), Cors Cross-domain processing, the successful access to the unified treatment after the failure of the unified processing.

The package of the query , this is more complicated, because there are OData, to his grammar has a common "translation", so that people who do not odata can quickly grasp. Finally reach, let the person feel not to have odata existence. This is easy to switch, OData is very powerful, but does not mean that will always use OData, which day is not, the client's calling code can not also follow the big face. Because just contact OData, so the package is just beginning to try, certainly a lot of imperfect places, feel everyone's advice! I thanked you first.

Add and modify the package is relatively simple, set a good type will not be anything, and then you can add some auxiliary functions according to their actual situation, such as setting the ID, set the tenant ID, and so on.

Delete It, it looks simple, but it's actually quite complicated. To put it simply, submitting a request is done; Complex said, is the physical deletion or tombstone, to delete before the data integrity of the judge, do not do cascading deletion. Now it's just a simple encapsulation.

This package, the time is more urgent, and the understanding of the new project is not enough, such as the API routing law has not mastered, but also want to encapsulate the URL, but can only temporarily give up.

Encapsulation of Ajax//The most basic layer of encapsulation Nature.ajax = function (ajaxinfo) {        //define default values  &nbs p; //type: "Get",              
         //access mode.    //datatype:nature.ajaxconfig.ajaxdatatype,     //Data type: JSON, JSONP, Text    //cache:true,                        /whether cache, default cache    //urlpara: {},// The parameter after the URL.
Will be added to the URL and will not be added to the form.    //formdata: {},//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: //rely on upper-level designation    //complement Ajaxinfo    //cache   

  if (typeof Ajaxinfo.cache = = "undefined") Ajaxinfo.cache = false;    //type     If (typeof Ajaxinfo.formdata = = "undefined") {       //ajaxinfo.type = ' get ';    } else {   &
nbsp;   //ajaxinfo.type = "POST";
        ajaxinfo.data = Ajaxinfo.formdata;    }       //handling URLs and Parameters     if (typeof ajaxinfo.url!= "undefined
") {       //var Tmpurlpara =" ";
       //var para = Ajaxinfo.urlpara;        //for (var key in para) {       //
    Tmpurlpara + + "&" + key + "=" + Para[key];        //}        //if (
AjaxInfo.url.indexOf ("?") >= 0) {       //   //original address has parameters, directly add        // &NBsp;  Ajaxinfo.url + = Tmpurlpara;        /} else {       //    //original address without parameters, into? plus        //    Ajaxinfo.url =
Tmpurlpara.replace ("&", "?");        //}         Ajaxinfo.url = Top.apiurl

+ AjaxInfo.url.replace (/{tenantid}/g, Top.tenantid);    }         //Processing beforesend     var beforesend = Aja
Xinfo.beforesend;        ajaxinfo.beforesend = function (XMLHttpRequest) {         if (typeof beforesend = = "function")            

Beforesend (token);
        Xmlhttprequest.setrequestheader ("Authorization", "bearer" + Top.token);    }   &nbsP Handling Xhrfields     if (typeof ajaxinfo.xhrfields = = "undefined") {      & nbsp
Ajaxinfo.xhrfields = {           //Allow cors to add cookies when Cross-domain access             withcredentials:true     
   };    } else {        if (typeof ajaxInfo.xhrFields.withCredentials = = "undefined") {           
AjaxInfo.xhrFields.withCredentials = true;        }    }    //cross-domain    with cors
  JQuery.support.cors = true;
       //Processing error     var error = Ajaxinfo.error;     ajaxinfo.error = function (Request, Textstatus, Errorthrown) {        //access failed, auto stop loadingAnimation, and give hints        //Get returned error hint         var
ErrMsg = Request.responsetext;         if (typeof errmsg!= "undefined") {      
      errmsg = eval ("+ errmsg +"));
            errmsg = errmsg.message;        }         Alert ("Submit" + Ajaxinfo.title + "When the error occurred!"
\r\n<br> "+ errmsg);         if (typeof top.spinstop = = "function")      
       Top.spinstop ();
        if (typeof error = = "function") error ();

   };
   //Processing success     var success = ajaxinfo.success;     ajaxinfo.success = function (data) {&NBSP;&NBSP;&NBSP;&Nbsp;   //Display debugging Information        //if (typeof parent. Debugset!= "undefined")        //    parent.

Debugset (Data.debug);         if (typeof success = = "function")       
      success (data);

           };

   //Start implementing Ajax     $.ajax (ajaxinfo);   };
Query data Nature.Ajax.find = function (ajaxinfo) {    ajaxinfo.type = ' get ';     var info = a
Jaxinfo.pagerinfo;    //processing URLs, paging and querying     if (typeof info!= "undefined") {     &

nbsp;  if (typeof ajaxinfo.data = = "undefined") Ajaxinfo.data = {};         if (typeof info.pagesize!= "undefined")      

       ajaxinfo.data["$top"] = info.pagesize;         if (typeof info.pageindex!= "undefined")      

       ajaxinfo.data["$skip"] = (info.pageindex-1) * info.pagesize;         if (typeof Info.orderby!= "undefined" && info.orderby!= "")  &

nbsp;          ajaxinfo.data["$orderby"] = Info.orderby;    } &NBSP;&NBSP;&NBSp Processing query conditions          //Handling return Events $orderby     var success = Ajaxinfo.succe

ss     ajaxinfo.success = function (data) {       //        //Judgment return information         if (typeof Data.message!=) Undefined ") {            alert (data.message);         } else {            if ( typeof success = = "function")               
  Success (data);

       }    };

    Nature.ajax (Ajaxinfo); };
Add Data Nature.Ajax.add = function (ajaxinfo) {    Ajaxinfo.type = "POST";    //Judge data.
 Add IDs and Tenantid.     if (typeof ajaxinfo.data!= "undefined") {        if (typeof AjaxInfo.data.id!= "undefined") {           
 AjaxInfo.data.id = "00000000000000000000000000000000";        }         if (typeof AjaxInfo.data.tenantId!= "undefined") {           
 AjaxInfo.data.tenantId = Top.tenantid;
 
        }    }     Nature.ajax (Ajaxinfo);
 
 };
 Modify Data Nature.Ajax.update = function (ajaxinfo) {    Ajaxinfo.type = "Put";     //Judge data.
 Add   Tenantid.     if (typeof ajaxinfo.data!= "undefined") {&NBSP;&Nbsp;              if (typeof ajaxInfo.data.tenantId!= " Undefined ") {            ajaxInfo.data.tenantId =
 Top.tenantid;        }    }         Nature.ajax (
 
 Ajaxinfo);
 
 };
 
 Delete Data Nature.Ajax.del = function (ajaxinfo) {    ajaxinfo.type = ' delete ';
 
     Nature.ajax (Ajaxinfo);
 };


Related Article

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

Starter Package

SSD Cloud server and data transfer for only $2.50 a month

Get Started >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.