Native Javascript encapsulation of an AJAX function to share

  • 2020-03-30 04:05:30
  • OfStack

Recent work involves a lot of ajax in the operation, was the background to do also want me to do. Now use the ajax function is a background personnel encapsulation - but he is also based on the jquery ajax, so left the jquery function is useless. And I think, the jquery ajax method is very perfect, can use directly, if have the jquery, so his ajax wouldn't have white don't have to. I lack is a can be used in the absence of the jquery ajax method.

So I also spent a day writing one that takes a parameter similar to calling a method like jquery's ajax. Let's call it XHR, because XHR =XMLHttpRequest.


/*
* Name: xhr,AJAX Packaging function
* Description: a ajax Invoke wrapper class , imitation jquery the ajax Call way
* Author: Ten years of light
*/
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) {
        var    
        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 appear and two successful callbacks will be executed (chrome et al will also execute onreadystatechange when synchronously requested)
            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: the request will not be initiated if it is not filled in, but if it is not filled in and sent is forced, it is not my fault
2. Method: 'GET' or 'POST', all uppercase, default GET
3. Data: the data to be sent should be attached, and the format is an object
4. Async: true by default
5. Type: the data type returned is only responseText or responseXML, the default is responseText
6.complete: the function that executes when the request completes
7. Success: the function that executes when the request succeeds
8. Error: the function to execute when the request fails

Note: the type parameter is not as rich as jquery's dataType, only native AJAX responseText or responseXML. If you are returning json data, you will need to work with the success function to convert the text to json.

Function description:

An instantiation of the XHR object has two function can be used, one is the send and call the method is: XHR. The send (), no parameters, its effect is the initiating process. If no url when the initialization, does not perform the send method, so that you can add the url in the back, and manually initiate the send - send if no url, then the request will fail and I don't have to deal with this wrong, wrong only you the change.

Another method is setData, the call method is xhr.setdata (data_obj), its parameter is an object. The function of setData method is to partially replace the value of XHR's data attribute, for example, there is a page:1 in xhr.data, you can use xhr.setdata ({page:2}) to update its value, but not affect the existing value of other attributes in the data.

Call method:


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

Note: don't write new

Features:

After project experience in this period of time, I found an ajax class should have a common characteristic: easy to repeat a request. When I write page ajax, such as project page every time to send the request, but sent the article in addition to the current page and a page number in the data, the other is not change. If such a request for many times, all want to repeat define the same parameter, no doubt is a waste of resources.

So the XHR function, have considered the function. Or take the paging example, we can finish when the page is loaded initialize an XHR object, saved as a variable a1, when a page request, the other parameters are unchanged, but the pageNumber changed, where you can call the XHR setData method, change the pageNumber.


a1.setData({pageNumber:2});

Note: the parameter of setData is also an object.

Of course, you can also replace data entirely:

A1. Data = {... };

Instead of just data, you can make more changes to a1, the XHR object that has been instantiated, such as changing the url, changing the success function, changing GET to POST, changing synchronous to asynchronous... After that, call a1.send(), and he'll make the request again as you set it up.

Of course, if it's a completely unrelated ajax request, there's no need to use the off-the-peg a1; we can instantiate another XHR, called a2 or something.

If you're not happy with the name XHR, you'll have to change it yourself.

Also provides compressed encryption version. Uncompressed version without comments about 2kb, compressed version 1.00 KB.


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)}}()


Related articles: