Share an AJAX function encapsulated by native Javascript, while javascript encapsulates ajax

Source: Internet
Author: User

Share an AJAX function encapsulated by native Javascript, while javascript encapsulates ajax

Recent work involves a lot of ajax operations, and I have to do what I have done in the background. currently, the ajax function is encapsulated by a background engineer, but it is based on jquery ajax, so leaving jquery is useless. in addition, I think jquery's ajax method is perfect and can be used directly. If jquery is available, its ajax will not be used for white. what I lack is an ajax method that can be used without jquery.

So I also spent a day writing one. The parameter and call method are similar to jquery's ajax. It's called xhr, because xhr = XMLHttpRequest.

Copy codeThe Code is as follows:
/*
* Name: xhr, AJAX encapsulation Function
* Description: an ajax call encapsulation class, which is similar to jquery's ajax call method.
* Author: 10-year 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 sending. Otherwise, a new synchronization request will execute two successful callbacks (chrome and other synchronous requests will also execute 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 ('asyncfalse ');
Complete ();
Root. success (req [type]);
}
}
Root. url & root. send ();
};
Return function (ops) {return new AJAX (ops );}
}();

Parameter description:

1. url
2. method: 'get' or 'post', all uppercase. The default value is GET.
3. data: The data to be sent with the format of an object
4. async: asynchronous or not. The default value is true.
5. type: Data type returned. Only responseText or responseXML is returned. The default value is responseText.
6. complete: The function executed when the request is complete.
7. success: The function executed when the request is successful
8. error: the function executed when the request fails.

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

Function Description:

An instantiated xhr object can be used by two functions: send and xhr. send (), no parameter, which is used to initiate the request process. if there is no url during initialization, The send method will not be executed, so that you can add a url later and manually initiate send -- if there is no url when sending, the request will fail and I have not handled the error. If the error occurs, you have found it yourself.

The other method is setData, and the calling method is xhr. setData (data_obj), whose parameter is an object. the setData method is used to partially replace the values in the data attribute of xhr, such as xhr. data already has a page: 1. You can use xhr. setData ({page: 2}) to update the value without affecting other attribute values in data.

Call method:
Copy codeThe Code is as follows:
Var a1 = xhr ({
Url: '2. php ',
Data :{
'Username': 'lix ',
'Password': '123 ',
'Gender': 'male ',
'Interset': 'play'
},
Async: false,
Method: 'get ',
Success: function (data ){
Var obj = JSON. parse (data );
//....
}
});

Note: Do not write new

Features:

After this time of project experience, I found that an ajax class should have a very common feature: it is convenient to initiate repeated requests. for example, when I write paging ajax in a project, a request is sent every time I flip the page, but the data sent will not change except the current page number and the number of entries per page. if you repeatedly define parameters for such requests, it is a waste of resources.

Therefore, this xhr function has been taken into account. in the case of paging, We can initialize an xhr object and save it as variable a1 when page loading is complete. When a page turning request is initiated, no other parameters are changed, however, if the pageNumber is changed, you can call the setData method of xhr to change the pageNumber.

Copy codeThe Code is as follows:
A1.setData ({pageNumber: 2 });

Note: The setData parameter is also an object.

Of course, you can also replace all data:

A1.data = {...};

Instead of data, you can make more changes to the instantiated xhr object a1, such as changing the url, replacing the success function, changing GET to POST, and synchronizing to asynchronous... After the replacement, call the a1.send () method, and then initiate the request again according to your settings.

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

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

In addition, the compressed encrypted version is provided. The uncompressed version removes the comment about 2 kb, and the compressed version is 1.00kb.
Copy codeThe 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 )}}()

Xhr is definitely not perfect. If you find it in use in the future, I will correct it in time. If you are uncomfortable or find it is insufficient, please do not hesitate to propose improvement suggestions.


Can the relationship between jquary javaScript ajax be said as follows: jquary completely encapsulates js and ajax?

Javascript is a language. Jquery is only a framework based on this language, which can simplify javascript coding. Of course, all functions in it are implemented through javascript. So what jquery can do is just a subset of javascript. Ajax is a technology. It can help us implement asynchronous refresh. This technology is mainly based on javascript.

Yes. This function is also encapsulated in the jquery framework. Therefore, you can use both native javascript to implement ajax and jquery.

Javascript uses Ajax send to pass html form objects

First, you must understand new Request ({...}). send ();
This Code defines an anonymous Request class instance and calls the send () method of the instance. Because he cannot see the Request () class code, he can only speculate based on his parameters, it should be the process of encapsulating an AJAX call.

Secondly, var myAjax = new Request ({...}). send (); in fact, it calls an AJAX submission process, and the background is im. php? Action = send. The transfer method is get, and the data source is the form of name = msg_form.

The data submitted by AJAX to the background is the same as that submitted by a common form to the background, and the data extraction method is the same. In php, $ _ GET ['xxx'] or $ _ POST ['xxx'] are different Based on the submission method.

Type = hidden data is submitted to the background, and the extraction method is the same.

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.