Home > Article > Web Front-end > Sharing an AJAX function encapsulated in native Javascript_javascript skills
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.
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);}
}();
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:
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.
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.