Encapsulation JS Implementation Ajax

Source: Internet
Author: User
Tags object error code header html header http post http request string versions

This two days carefully understand the Ajax, and then the packaging for a while, if there is anything wrong, please advise, thank you!

Ajax

AJAX = Asynchronous JavaScript and XML (asynchronous JavaScript and XML).

AJAX is not a new programming language, but a new way of using existing standards.

AJAX is the art of exchanging data with the server and updating parts of the Web page without reloading the entire page.

The advent of XHR provides a fluent interface for sending requests to the server and analyzing the server response. Be able to get more information from the server asynchronously, which means that the user can simply trigger an event and update the server's latest data without refreshing the page.
While x in AJAX represents XML, Ajax communication is not about data format, which means that the technology does not necessarily use XML.

Detailed criteria can go to w3c:http://www.w3school.com.cn/ajax/ajax_intro.asp

The first is to create a XHR object:

function Createxhr () {
if (typeof xmlhttprequst!== ' undefined ') {
return new XMLHttpRequest ();
else if (typeof activexobject!== ' undefined ') {//otherwise judge ActiveXObject, IE6, and the following
if (typeof arguments.callee.activeXString!= ' string ') {
var versions = [' MSXML2. xmlhttp.6.0 ', ' MSXML2. xmlhttp.3.0 ', ' MSXML2. XMLHTTP '];
for (var i = 0, len = versions.length i < len; i++) {
try {
New ActiveXObject (Versions[i]);
arguments.callee.activeXString = Versions[i];
Break
catch (ex) {
Jump over
}
}
}
return new ActiveXObject (arguments.callee.activeXString);
} else{
throw new Error (' No XHR object available ');
}
}

ie7+, Firefox, Opera, Chrome, and Safari all support native XHR objects, in which XHR objects can be directly instantiated XMLHttpRequest, if IE6 and below, then we need to use ActiveX object is implemented through the MSXML library. In a low version, IE may encounter three different versions of the Xhr object, namely Msxml2.xmlhttp, msxml2.xmlhttp.3.0, msxml2.xmlhttp.6.0. Put these three different versions in an array, and then loop through the attempt to create a Xhr object, and success jumps out of the loop and throws an error if none is supported. JavaScript Advanced Programming (3rd Edition) can be accessed specifically.

Here we're going to encapsulate, and then by introducing the call:

Invoke Ajax
Jr.ajax ({
Method: ' Post ',
URL: ' demo.php ',
Data: {
' Name ': ' JR ',
' Age ': 22
},
timeout:5000,
Success:function (response) {
alert (response);
},
Error:function (Status,statustext) {
Alert (' Get data Error! Error code: ' + status + ', error message: ' + statustext ';
},
Complete:function () {
Alert ("Request Complete");
},
Async:true
});

for encapsulation, I searched some information, but still not very thorough, so if I have a problem with the package, I also hope that, thank you very much!

Jr.ajax = function (obj) {
Initializes an object and replaces it with a default value when it is not filled in
obj = {
Request method, default post
Method:obj.method "POST",
The requested URL
Url:obj.url "",
Request data Parameters Sent
Data:obj.data "",
The time that the request timed out, default 5 seconds
Timeout:obj.timeout 5000,
function to execute when the request succeeds
success:obj.success function () {},
function to execute when request fails
Error:obj.error function () {},
The function that executes when the request completes (both successful and unsuccessful)
Complete:obj.complete function () {},
Synchronous or asynchronous, default asynchronous
Async:obj.async true
};
Creating XHR Objects
var xhr = (function () {
if (typeof xmlhttprequst!== ' undefined ') {
return new XMLHttpRequest ();
else if (typeof activexobject!== ' undefined ') {//otherwise judged ActiveXObject
if (typeof arguments.callee.activeXString!= ' string ') {
var versions = [' MSXML2. xmlhttp.6.0 ', ' MSXML2. xmlhttp.3.0 ', ' MSXML2. XMLHTTP '];
for (var i = 0, len = versions.length i < len; i++) {
try {
New ActiveXObject (Versions[i]);
arguments.callee.activeXString = Versions[i];
Break
catch (ex) {
Jump over
}
}
}
return new ActiveXObject (arguments.callee.activeXString);
} else{
throw new Error (' No XHR object available ');
}
})();
var requestdone = false,//Flag request is complete
Using JS random string to solve the problem of Internet Explorer's second default get cache
Obj.url = Obj.url + '? rand= ' + math.random ();
Converts a name-value pair to a string
Obj.data = (function (data) {
var arr = [];
for (var i in data) {
Problems caused by special character Fu can be encoded using encodeuricomponent ()
Arr.push (encodeURIComponent (i) + ' = ' + encodeURIComponent (data[i));
}
Return Arr.join (' & ');
}) (Obj.data);
If a GET request, the data is appended to the URL
if (obj.data!== ' && obj.method = = ' Get ') {
Obj.url + = Obj.url.indexOf ('? ') = = 1? '? ' + obj.data: ' & ' + obj.data;
}
When using the XHR object, you must first call the open () method.
It accepts three parameters: the request type (get, post), the requested URL, and whether the representation is asynchronous.
Xhr.open (Obj.method, Obj.url, Obj.async);
Initializes a 5-second callback function to cancel the request (if not yet completed)
settimeout (function () {
Requestdone = true;
}, Obj.timeout);

if (Obj.async = = True) {//true is asynchronous, false indicates synchronous
When using an asynchronous call, you need to trigger the ReadyStateChange event
Listening for updates to the status of a document
Xhr.onreadystatechange = function () {
if (xhr.readystate = = 4 &&!requestdone) {//To determine whether the object's state is interactively completed
Callback (); Callback
}
};
}
if (Obj.method = = ' Post ') {
The Post method requires you to set the HTTP request header to mimic the form submission.
After the open method, before the Send method.
Xhr.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded ');
Xhr.send (Obj.data); Post method to place the data in the Send () method
} else {
Xhr.send (NULL); The Get method fills in null
}
if (Obj.async = = False) {//sync
Callback ();
}
function callback () {
if (Xhr.status = = 200) {//To determine whether HTTP interaction succeeded, 200 indicates success
Obj.success (Xhr.responsetext); Success
} else {
Obj.error (Xhr.status,xhr.statustext)//failure
}
Call Completion callback function
Opt.complete ();
Avoid memory leaks, cleaning up documents
XHR = null;
}

return this;
};

If you have their own encapsulated JS library, this can be introduced as a plug-in, as for this, I will continue to work hard, will be used to the JS method of packaging into their own JS library, refueling!

Comparison of Post and get methods in Ps:ajax requests:

Post method

Get mode

Execute each time Same address does not repeat execution
Not cacheable can be cached
With the HTTP post mechanism, the fields in the form are placed in the HTML header with their contents in the URL address that the action attribute refers to, and the user does not see the process Add the parameter data queue to the URL that refers to the action attribute of the submission form, and the value corresponds to each field one by one in the form, which is visible in the URL
Server-side uses Request.Form to obtain submitted data Server-side uses Request.QueryString to get the value of a variable
The amount of data transmitted is large, and is generally default to Unrestricted, but in theory, depending on the server The amount of data transferred is small and cannot be greater than 2KB
High Security Very Low security
When method is post, the list of parameters in the back of the action page is not ignored, so it is different. When method is get, the list of arguments behind the action page is ignored
Data is placed in the HTTP body, the organization of more than one, there are & connection, but also the way of separator, can hide parameters, transfer large numbers of data, more convenient It adds data to the URL, which is passed to the server in this way, usually using a question mark? Represents the end of the URL address and the beginning of the data parameter, with each data parameter appearing in the form of "name = value", with the & distinction between the parameters


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.