Recently, I have involved a lot of ajax operations, and I have to do what I should do in the background. The ajax function I use now is encapsulated by a background personnel - but it is based on jquery ajax, so it will be useless without jquery. And I think the ajax method of jquery is very complete and can be used directly. If there is jquery, then his ajax will not be used in vain. What I lack is an ajax method that can be used without jquery.
So I also spent a day writing one, the parameters and the calling method are similar to jquery's ajax. It's called xhr, because xhr=XMLHttpRequest.
The code copy is as follows:
/*
* Name: xhr,AJAX encapsulation function
* Description: A Javax call encapsulation class, imitating jquery's ajax call method
* 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, etc. will also execute onreadystatechange when synchronizing the request)
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: The request address. You can not fill in it, and the request will not be initiated. But if you don’t fill in it and force it to send, I won’t blame you for any mistakes.
2.method: 'GET' or 'POST', all capitalized, default GET
3.data: The data to be sent is an object
4.async: Whether it is asynchronous, default true
5.type: The returned data type is only responseText or responseXML, and the default responseText
6.complete: Functions executed when the request is completed
7.success: Functions executed when the request is successful
8.error: Function executed when the request fails
Note: The type parameters are not as rich as jquery's dataType, only responseText or responseXML in native AJAX. If the json data is returned, you need to handle it yourself in the success function to convert text into json.
Function description:
There are two functions to use for an instantiated xhr object. One is send. The call method is: xhr.send(), with no parameters. Its function is to initiate the request process. If there is no url during initialization, the send method will not be executed, so you can add url later and initiate send manually - If there is no url during send, the request will fail and I did not handle this error. Only you can find the error yourself.
Another method is setData, the call 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.data. For example, there is already a page:1 in xhr.data. You can use xhr.setData({page:2}) to update its value without affecting other attribute values that already exist in data.
Calling method:
The code copy is as follows:
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: No need to write new
Featured introduction:
After this period of project experience, I found that an ajax class should have a very common feature: it is convenient to initiate requests repeatedly. For example, when I write a page of ajax in a project, I have to send a request every time I turn the page, but the data sent will not change except for the current page number and the number of each page. If you have to repeatedly define those unchanged parameters, it is undoubtedly a waste of resources.
So this xhr function has already considered this function. Take the example of pagination. We can initialize an xhr object when the page is loaded and save it as a variable a1. When a page turn request is initiated, no other parameters have changed, but the pageNumber has changed. At this time, we can call the setData method of xhr to change pageNumber.
The code copy is as follows:
a1.setData({pageNumber:2});
Note: The parameter of setData is also an object.
Of course, you can also replace data completely:
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, changing GET to POST, and changing synchronously to asynchronous... After changing, call the a1.send() method, and 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 force this ready-made a1. We can instantiate another xhr called a2 or something.
If you are not satisfied with the name xhr, you can only change it yourself.
In addition, it provides a compressed encrypted version. The uncompressed version removes the comments about 2kb, and the compressed version is 1.00kb.
The code copy 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 incompleteness in xhr. If you find it during use in the future, I will correct it in time. If you are not happy with it or find it insufficient, please give suggestions for improvement.