How does native js implement AJAX, JSONP, and DOM loading completion events?

Source: Internet
Author: User
Native JS implements AJAX, JSONP, and DOM loading completion events 1. JS native Ajax

Ajax: A Data Request Method. You do not need to refresh the entire page;
The core of ajax is the XMLHttpRequest object;
Ajax request process: Create an XMLHttpRequest object, connect to the server, send requests, and receive response data;

The following is a simple encapsulation of a function, which will be explained later.

Ajax ({url :". /TestXHR. aspx ", // request address type:" POST ", // Request Method data: {name:" super ", age: 20}, // request parameter dataType: "json", success: function (response, xml) {// code executed after the operation is successful}, fail: function (status) {// code executed after the failure is put here}); function ajax (options) {options = options |{}; options. type = (options. type | "GET "). toUpperCase (); options. dataType = options. dataType | "json"; var params = formatParams (option S. data); // create-non-IE6-Step 1 if (window. XMLHttpRequest) {var xhr = new XMLHttpRequest ();} else {// IE6 and earlier browsers var xhr = new ActiveXObject ('Microsoft. XMLHTTP ');} // receive-Step 3 xhr. onreadystatechange = function () {if (xhr. readyState = 4) {var status = xhr. status; if (status> = 200 & status <300) {options. success & options. success (xhr. responseText, xhr. responseXML);} else {options. fail & o Ptions. fail (status) ;}}// connect and send-Step 2 if (options. type = "GET") {xhr. open ("GET", options. url + "? "+ Params, true); xhr. send (null);} else if (options. type = "POST") {xhr. open ("POST", options. url, true); // sets the content type xhr when the form is submitted. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); xhr. send (params) ;}}// the formatting Parameter function formatParams (data) {var arr = []; for (var name in data) {arr. push (encodeURIComponent (name) + "=" + encodeURIComponent (data [name]);} arr. push ("v =" + Math. random ()). replace (". "); return arr. join ("&");}

1. Create

1.1. IE7 and later versions support native XHR objects, so you can directly use: var oAjax = new XMLHttpRequest ();

1.2. in IE6 and earlier versions, XHR objects are implemented through an ActiveX object in the MSXML library. Some books detail three different versions of such objects in IE, namely, MSXML2.XMLHttp and MSXML2.XMLHttp. 3.0 and MSXML2.XMLHttp. 6.0. In my personal experience, you can directly use the following statement to create var oAjax = new ActiveXObject ('Microsoft. XMLHTTP ');

2. Connect and send

2.1. Three parameters of the open () function: Request Method, request address, and asynchronous request (the synchronous request is rare and has never been used yet );

2.2. the GET request uses the URL parameter to submit data to the server, and the post request uses the data as the send parameter to submit the data to the server;

2.3 In the POST request, you must set the content type for form submission before sending data;

2.4 The parameters submitted to the server must be encoded by the encodeURIComponent () method. In fact, both the key and value must be encoded in the form of "key = value" in the parameter list, because it contains special characters. A "v = xx" string is added to the parameter list for each request. In this way, the request is directly sent to the server to reject the cache.

EncodeURI (): used to encode the entire URI. It does not encode special characters belonging to the URI, such as the colon, forward slash, question mark, and well number. Its corresponding decoding function decodeURI ();
EncodeURIComponent (): used to encode a part of the URI and encode any non-standard characters it discovers. Its decoding function is decodeURIComponent ();

3. Receive

3.1 after a response is received, the response data is automatically filled with the XHR object. The related attributes are as follows:
ResponseText: Body content returned by the response, which is of the string type;
ResponseXML: If the response content type is "text/xml" or "application/xml", the corresponding xml data is saved in this attribute, which is the document type corresponding to XML;
Status: the HTTP status code of the response;
StatusText: HTTP status description;

3.2 The readyState attribute of the XHR object indicates the current active phase of the Request/response process. The value of this attribute is as follows:
0-not initialized. The open () method has not been called;
1-start, the open () method is called, and the send () method is not called;
2-send. The send () method has been called and no response has been received;
3-received, some response data has been received;
4-complete. All response data has been received;

As long as the value of readyState changes, the readystatechange event will be called. (In fact, to be logically smooth, you can put readystatechange after sending. Because network communication is required when sending requests to the server, it takes time, it is also possible to specify the readystatechange event handler after sending, which is usually used in this way, but to standardize compatibility with cross-browser, you should specify it before open ).

3.3 In the readystatechange event, determine whether the response is received and whether the server successfully processes the request. xhr. status indicates the status code. If the status code starts with 2, it is successful. 304 indicates that it is obtained from the cache. The preceding Code adds a random number to each request, therefore, it does not take values from the cache, so this status does not need to be determined.

4. ajax requests cannot be cross-origin!

Ii. JSONP

JSONP (JSON with Padding) is a cross-origin request method. The main principle is to use the script tag to enable cross-origin requests. The src attribute of the script is used to send the request to the server. The server returns the js Code, and the webpage accepts the response, and then runs the Code directly, this works the same way as referencing an external file using a script tag.

JSONP consists of two parts: callback function and data. The callback function is generally controlled by the webpage side and sent as a parameter to the server side. The server side returns the function and data in a string.

For example, create a script tag on the web page and assign the src value to the http://www.superfiresun.com/json? Callback = process. At this time, the webpage initiates a request. The data to be returned by the server puts together the parameters of the best function. The format of the data returned by the server is similar to "process ({'name': 'superfiresun'})", and the webpage receives the response value, because the requester is a script, it is equivalent to directly calling the process method and passing in a parameter.

Looking at the data returned by the response, JSONP has an additional callback function than ajax.

Function jsonp (options) {options = options | |{}; if (! Options. url |! Options. callback) {throw new Error ("the parameter is invalid");} // create a script tag and add it to var callbackName = ('jsonp _ '+ Math. random ()). replace (". "," "); var oHead = document. getElementsByTagName ('head') [0]; options. data [options. callback] = callbackName; var params = formatParams (options. data); var OS = document. createElement ('script'); oHead. appendChild (OS); // create the jsonp callback function window [callbackName] = function (json) {oHea D. removeChild (OS); clearTimeout (OS. timer); window [callbackName] = null; options. success & options. success (json) ;}; // sends the request to the OS. src = options. url + '? '+ Params; // timeout processing if (options. time) {OS. timer = setTimeout (function () {window [callbackName] = null; oHead. removeChild (OS); options. fail & options. fail ({message: "timeout"}) ;}, time) ;}; // format the Parameter function formatParams (data) {var arr = []; for (var name in data) {arr. push (encodeURIComponent (name) + '=' + encodeURIComponent (data [I]);} return arr. join ('&');}

1. Because the src attribute of the script TAG takes effect only when it is set for the first time, the script tag cannot be reused. Therefore, the script tag must be removed after each operation is completed;

2. In the JSONP request method, the parameter still needs to be encoded;

3. If no timeout is set, the request is successful or failed;

3. Simulate the ready () event in JQuery

1. The DOMContentLoaded event is executed immediately after the DOM tree is loaded. It will always be executed before the load.
IE9 +, FF, Chrome, Safari3.1 +, and Opera9 + all support this event.

For browsers that do not support this event, use the following code:

SetTimeout (function (){
// Code block}, 0 );

The DOMContentLoaded event can only be added at the DOM2 level, that is, it can be used only when addEventListener ()/attachEvent () is added. The event object does not provide any additional information.

2. readystatechange event

IE provides this event for some parts of the DOM document (unlike the readystatechange event of the XHR object), which aims to provide information about the loading status of the document or element, however, the behavior of this event is sometimes unpredictable. All objects that support this event have a readyState attribute. Note that it is not an event object. IE, Firefox4 +, and Opera support this event.

The value of the readyState attribute is as follows:
"Uninitialized"-not initialized: the object exists but has not been initialized;
"Loading"-loading: the object is loading data;
"Loaded"-after loading, the object loads data;
"Interactive"-interaction: the object can be operated, but it has not been fully loaded;
"Complete"-complete: the object has been loaded;

2.1. Not all objects will go through the readyState stages. If this stage does not apply to an object, the object may be skipped and there is no rule on which stage applies to which object. This means that the readystatechange event is often less than four times, and the corresponding value of readyState is not consecutive.

2.2 for documents, the interactive and complete phases trigger the readystatechange event at roughly the same time as DOMContentLoaded;

The trigger sequence of the load event and readystatechange event varies according to the number of external resources on the page. That is to say, the readystatechange event will not be executed until the load event occurs. The more external resources, the more favorable the readystatechange event.

The order of interactive and complete is also inconsistent, and anyone may execute it first. The more external resources referenced, the more favorable the interaction stage. Therefore, in order to execute the code as early as possible, both States must be determined at the same time.

3. doScroll
IE5.5 + support. When a page contains a scroll bar, you can use doScroll ("right")/doScroll ("down") to move the scroll bar. This method can be used only after DOM loading is complete, therefore, in earlier IE browsers, you can use this attribute to determine whether the DOM structure is fully loaded. This attribute is used to simulate the solution in jquery.

Function ready (readyFn) {// non-IE browser if (document. addEventListener) {document. addEventListener ('domcontentloaded', function () {readyFn & readyFn () ;}, false) ;} else {// solution 1 and 2 which are used quickly? var bReady = false; // solution 1 document. attachEvent ('onreadystatechang', function () {if (bReady) {return;} if (document. readyState = 'complete' | document. readyState = "interactive") {bReady = true; readyFn & r EadyFn () ;};}); // solution 2 // jquery will also worry that doScroll will expire in iframe. This is to determine whether the current page is placed in iframe. if (! Window. frameElement) {setTimeout (checkDoScroll, 1);} function checkDoScroll () {try {document.doc umentElement. doScroll ("left"); if (bReady) {return;} bReady = true; readyFn & readyFn ();} catch (e) {// continuously check whether doScroll is available-whether the DOM structure has been loaded setTimeout (checkDoScroll, 1 );}};}};

Note:
SetTimeout (checkDoScroll, 1); the objective is to allow the browser to execute the checkDoScroll function as soon as possible. The interval is set to 1 ms, which is unlikely for the current browser. Each browser has its own default minimum interval. Even if the time is set to the minimum interval, it only indicates that after these times, JavaScript will add checkDoScroll to the execution queue, if the JavaScript process is idle, the code is executed immediately.

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.