Home  >  Article  >  Web Front-end  >  Sharing an AJAX function encapsulated in native Javascript_javascript skills

Sharing an AJAX function encapsulated in native Javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:34:181255browse

My recent work involves a lot of ajax operations, and I have to do the things that should be done in the background. The ajax function used now is encapsulated by a background person - but it is based on jquery's ajax. So the function without jquery is useless. And I think that the ajax method of jquery is very complete and can be used directly. If you already have jquery, then its ajax will not be used in vain. What I am missing is An ajax method that can be used without jquery.

So I also spent a day writing one. The parameters and calling method are similar to jquery's ajax. Let's call it xhr, because xhr=XMLHttpRequest.

Copy code The code is as follows:

/*
* Name: xhr,AJAX wrapper function
* Description: An ajax calling encapsulation class, imitating jquery’s ajax calling method
* Author: Ten Years Lamp
*/
var xhr = function () {
var
ajax = function () {
           return ('XMLHttpRequest' in window) ? function () {
                    return new XMLHttpRequest();
               } : function () {
               return new ActiveXObject("Microsoft.XMLHTTP");
}
}(),
formatData= function (fd) {
        var res = '';
for(var f in fd) {
               res = f '=' fd[f] '&';
}
          return res.slice(0,-1);
},
AJAX = function(ops) {
                                                     root = this,
          req = ajax();
root.url = ops.url;

         root.type = ops.type || 'responseText';
          root.method = ops.method || 'GET';
          root.async = ops.async || true;                                 root.data = ops.data || {};
root.complete = ops.complete || function () {};
root.success = ops.success || function(){};
root.error = ops.error || function (s) { alert(root.url '->status:' s 'error!')};
         root.abort = req.abort;
          root.setData = function (data) {
               for(var d in data) {
                    root.data[d] = data[d];
            }
}
root.send = function () {
          var datastring = formatData(root.data),
                sendstring,get = false,
async = root.async,
             complete = root.complete,
            method = root.method,
            type=root.type;
If(method === 'GET') {
                      root.url ='?' datastring;
                    get = true;
            }
                req.open(method,root.url,async);
               if(!get) {
                 req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                      sendstring = datastring;
                                                                       

                         //Reset the onreadystatechange method before send, otherwise a new synchronization request will occur and two successful callbacks will be executed (chrome, etc. will also execute onreadystatechange during synchronization requests)
                req.onreadystatechange = async ? function () {
                           // console.log('async true');
If (req.readyState ==4){
complete();
If(req.status == 200) {
                                 root.success(req[type]);
                      } else {
Root.error(req.status);
                                                                                                                                                                              ​                  }
               } : null;
                req.send(sendstring);
               if(!async) {
//console.log('async false');
complete();
                    root.success(req[type]);
            }
}
         root.url && root.send();                                                               };
Return function(ops) {return new AJAX(ops);}
}();


Parameter description:

1.url: Request address. If you don’t fill it in, the request will not be initiated. But if you don’t fill it in and force send, you don’t blame me if something goes wrong

2.method: ‘GET’ or ‘POST’, all capital letters, default GET

3.data: The data to be sent is attached, the format is an object
4.async: Whether to be asynchronous, default true
5.type: The returned data type is only responseText or responseXML. The default is responseText
6.complete: Function executed when the request is completed
7.success: Function executed when the request is successful
8.error: Function executed when the request fails

Note: The type parameter is not as rich as jquery's dataType. It only has responseText or responseXML in native AJAX. If json data is returned, you need to process it yourself in the success function to convert text into json.

Function description:

An instantiated xhr object has two functions available, one is send, the calling method is: xhr.send(), no parameters, its function is to initiate the request process. If there is no url during initialization, it will not be executed. send method, so that you can add the url later and initiate the send manually - if there is no url when sending, the request will fail and I did not handle this error. You will only find the error yourself.

Another method is setData. The calling method is xhr.setData(data_obj), and its parameter is an object. The function of the setData method is to partially replace the value in the data attribute of xhr. For example, there is already a page in xhr.data: 1. You can use xhr.setData({page:2}) to update its value without affecting other attribute values ​​​​that already exist in data.

Calling method:


Copy code The code is as follows:

var a1 = xhr({
                                                                                                                                                                                                                                  data:{               'username':'lix',               'password':'123456',
            'gender':'male',
             'interset':'play'
},
async:false,
Method:'GET',
Success: function (data) {
          var obj = JSON.parse(data);
                  //....
}
});


Note: No need to write new
Feature introduction:
After this period of project experience, I found that an ajax class should have a very common feature: to facilitate repeated requests. For example, when I wrote pagination ajax in the project, a request had to be sent every time the page was turned, but Except for the current page number and the number of items per page, the other data will not change. If you make multiple such requests, you have to repeatedly define those unchanged parameters, which is undoubtedly a waste of resources.

So this xhr function has already considered this function. Taking the example of paging, we can initialize an xhr object when the page is loaded and save it as variable a1. When a page turning request is initiated, other None of the parameters have changed, but the pageNumber has changed. At this time, you can call the setData method of xhr to change the pageNumber.

Copy code The code is as follows: a1.setData({pageNumber:2});


Note: The parameter of setData is also an object.
Of course, you can also replace the entire data:

a1.data = {…};

Not just data, you can make more changes to the instantiated xhr object a1, such as changing the url, changing the success function, GET to POST, synchronous to asynchronous... After changing, call again a1.send() method, it will initiate the request again according to your settings.

Of course, if it is another ajax request that is completely unrelated, there is no need to use this ready-made a1. We can instantiate another xhr and call it a2 or something.

If you are not satisfied with the name xhr, then you have to change it yourself.

A compressed and encrypted version is also provided. The uncompressed version is about 2kb with comments removed, and the compressed version is 1.00kb.


Copy code The code is as follows: var xhr=function(){var e=function(){return "XMLHttpRequest" in window?function(){return new XMLHttpRequest}:function(){return new ActiveXObject("Microsoft.XMLHTTP")}}(),t =function(e){var t="";for(var n in e){t =n "=" e[n] "&"}return t.slice(0,-1)},n=function( n){var r=this,i=e();r.url=n.url;r.type=n.type||"responseText";r.method=n.method||"GET";r. async=n.async||true;r.data=n.data||{};r.complete=n.complete||function(){};r.success=n.success||function(){} ;r.error=n.error||function(e){alert(r.url "->status:" e "error!")};r.abort=i.abort;r.setData=function(e ){for(var t in e){r.data[t]=e[t]}};r.send=function(){var e=t(r.data),n,s=false,o= r.async,u=r.complete,a=r.method,f=r.type;if(a==="GET"){r.url="?" e;s=true}i.open( a,r.url,o);if(!s){i.setRequestHeader("Content-type","application/x-www-form-urlencoded");n=e}i.onreadystatechange=o?function( ){if(i.readyState==4){u();if(i.status==200){r.success(i[f])}else{r.error(i.status)}}}: null;i.send(n);if(!o){u();r.success(i[f])}};r.url&&r.send()};return function(e){return new n( e)}}()


There must be some imperfections in xhr. If found in future use, I will correct them in time. If you are not happy with it or find it insufficient, please feel free to provide suggestions for improvement.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn