Native JavaScript encapsulates an AJAX function to share _javascript tips

Source: Internet
Author: User

The most recent work involves a lot of Ajax operations, and I should have done the backstage thing. The Ajax function that is now used is encapsulated by a backstage person-but he is also based on jquery Ajax, so the function of leaving jquery has no effect. And I think that jquery's ajax approach is perfect, and can be used directly, if there is jquery, then his Ajax will not be white. What I'm missing is an AJAX approach that can be used without jquery.

So I also spent one day writing a parameter and calling methods similar to jquery's Ajax. Call it xhr, because Xhr=xmlhttprequest.

Copy Code code as follows:

/*
* Name:xhr,ajax Package function
* Description: An AJAX call Encapsulation class, the Ajax invocation mode of jquery
* 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) {
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 sync request will perform a two successful callback (Chrome, and so on when the sync request executes onreadystatechange)
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. Can not fill out, the request will not be initiated, but if not fill and forcibly send, out of the wrong do not blame me
2.method: ' Get ' or ' POST ', all caps, default get
3.data: The data to be sent with the format is an object
4.async: Asynchronous, Default True
5.type: Returned data type, only ResponseText or responsexml, default ResponseText
6.complete: function to execute when request completes
7.success: function to execute when request succeeds
8.error: function to execute when request fails

Note: The type parameter is not as rich as jquery's datatype, only native Ajax has ResponseText or responsexml. If you return the JSON data, You need to work with the success function to turn text into JSON.

Function Description:

An instantiated XHR object has two functions to use. One is send, the method is called: Xhr.send (), no parameters, and its effect is to initiate the request process. If no URL is initialized, the Send method is not executed, so you can add the URL later and manually initiate the send- -If send does not have a URL, then the request will fail and I have not handled the error, only you find the wrong.

Another method is SetData, the calling method is Xhr.setdata (Data_obj), and its argument is an object. The effect of the SetData method is to replace the value in the XHR's data attribute locally, such as a page:1 in Xhr.data, where you can update his value with Xhr.setdata ({page:2}) without affecting other property values that already exist in data.

Call Method:

Copy Code code as follows:

var A1 = XHR ({
url:http://www.jb51.net/article/' 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 time of project experience, I found that an Ajax class should have a very common feature: it is easy to repeat the request. For example, when I write page Ajax in a project, I send a request every time it is paged, but in addition to the current page number and the number of pages per page, The rest will not change. If multiple requests are repeated, it is no doubt a waste of resources to define those immutable parameters.

So this XHR function has been taken into account. Or take the pagination example, we can initialize the page when the completion of the initialization of a XHR object, save as a variable a1, when the paging request, the other parameters are not changed, but PageNumber changed, At this point you can call the Xhr SetData method, the pagenumber to get rid of.

Copy Code code as follows:

A1.setdata ({pagenumber:2});

Note: The SetData parameter is also an object.

Of course, you can also replace the data:

A1.data = {...};

Not just data, you can make more changes to the A1 of this already instantiated XHR object, such as changing the URL, replacing the success function, get replaced by post, synchronous Exchange asynchronous ... When you're done, call the A1.send () method again, and he will initiate the request again according to your settings.

Of course, if it is completely unrelated to another AJAX request, there is no need to use this ready-made A1. We can instantiate a xhr, called A2 or something.

If you are not satisfied with the name of XHR, you have to get rid of it yourself.

In addition, the compression version is provided. Uncompressed version of the note about 2KB, compressed 1.00kb.

Copy Code code 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)}} ()

XHR must have imperfect place, in the future use if found, I will promptly amend. If you are not comfortable with or found inadequate, please do not hesitate to suggest improvements.

Related Article

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.