Native JS sends asynchronous data requests, js asynchronous

Source: Internet
Author: User

Native JS sends asynchronous data requests, js asynchronous

Asynchronous data requests are sometimes required for projects. However, if there is no framework dependency at this time, native JS is required for asynchronous data requests. At this time, there are only two request methods: AJAX and JSONP. Simple encapsulation of asynchronous requests through Native JS.

AJAX

AJAX is a data request method that allows you to update data on a local page without refreshing the entire page. The core of AJAX is the XMLHttpRequest object. The main request process is as follows:

  • Create an XMLHttpRequest object (new)
  • Connect to the server (open)
  • Send)
  • Onreadystatechange)

Directly paste code without speaking

/*** Request in JSON format * @ param {[type]} params [description] * @ return {[type]} [description] */ajaxJSON (params) {params. type = (params. type | 'get '). toUpperCase (); params. data = params. data ||{}; var formatedParams = this. formateParams (params. data, params. cache); var xhr; // create the XMLHttpRequest object if (window. XMLHttpRequest) {// non-IE6 xhr = new XMLHttpRequest ();} else {xhr = new ActiveXObject ('Microsoft. XML HTTP ');} // the asynchronous status changes and the response data is received xhr. onreadystatechange = function () {if (xhr. readyState = 4 & xhr. status = 200) {if (!! Params. success) {if (typeof xhr. responseText = 'string') {params. success (JSON. parse (xhr. responseText);} else {params. success (xhr. responseText) ;}} else {params. error & params. error (status) ;}} if (params. type = 'get') {// connect to the server xhr. open ('get ',(!! FormatedParams? Params. url + '? '+ FormatedParams: params. url), true); // send the request xhr. send ();} else {// connect to the server xhr. open ('post', params. url, true); xhr. setRequestHeader ('content-type', 'application/x-www-form-urlencoded'); // send the request xhr. send (formatedParams );}}, /*** format the data ** @ param {Obj} data the data to be formatted * @ param {Boolean} Does isCache Add a random parameter * @ return {String} to the returned String */formateParams: function (data, isCache) {var arr = []; for (var name in data) {arr. push (encodeURIComponent (name) + '=' + encodeURIComponent (data [name]);} if (isCache) {arr. push ('v = '+ (new Date ()). getTime ();} return arr. join ('&');}

IE7 and later versions support native XHR objects, so you can directly use: var oAjax = new XMLHttpRequest ();. In IE6 and earlier versions, XHR objects are implemented through an ActiveXObject object in the MSXML library.

The xhr open function is used to connect to the server. It mainly receives three parameters: Request Method, request address, and asynchronous request (generally asynchronous requests ). There are two request methods: GET and POST. GET submits data to the server through URL, and POST sends data to the server as a parameter of the send method.

The onreadystatechange function binds the status change function to xhr to detect changes in readyState of xhr. After the asynchronous transmission is successful, the value of readyState changes from 0 to 4, and the onreadystatechange event is triggered. The attributes and status of readyState are as follows:

0 (not initialized) the object has been created, but has not been initialized (the open method has not been called)
1 (initialization) the object has been created and the send method has not been called
2 (send data) The send method has been called, but the current status and http header are unknown.
3 (in data transmission) Some data has been received. Because the response and http headers are incomplete, an error occurs when retrieving part of data through responseBody and responseText.
4. After receiving the data, you can use responseBody and responseText to obtain the complete response data.

In the readystatechange event, first determine whether the response is received and then whether the server has successfully processed 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.

JSONP

If the above XMLHttpRequest object is used to send the request that requires cross-origin, although the send function is called, The xhr status is always 0 and the onreadystatechange event is not triggered, in this case, the JSONP request method is used.

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.test.com/json? Callback = process. At this time, the webpage initiates a request. The data to be returned by the server is input as a function parameter. The format of the data returned by the server is similar to "process ({'name: 'xieyufei'})", 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.

Directly paste the code without talking.

/*** Request through JSONP * @ param {[type]} params [description] * @ return {[type]} [description] */ajaxJSONP (params) {params. data = params. data ||{}; params. jsonp = params. jsonp | 'callback'; // sets the callback parameter name and parameter value passed to the backend. var callbackName = 'jsonp _ '+ (new Date ()). getTime (); params. data [params. jsonp] = callbackName; var formatedParams = this. formateParams (params. data, params. cache); // create a script tag and insert it into the page var head = Document. getElementsByTagName ('head') [0]; var script = document. createElement ('script'); head. appendChild (script); // create the jsonp callback function window [callbackName] = function (json) {head. removeChild (script); clearTimeout (script. timer); window [callbackName] = null; params. success & params. success (json) ;}; // sends the request script. src = (!! FormatedParams? Params. url + '? '+ FormatedParams: params. url); // to determine whether the request is successful, set timeout for processing if (params. time) {script. timer = setTimeout (function () {window [callbackName] = null; head. removeChild (script); params. error & params. error ({message: 'timeout'}) ;}, params. time );}}

When setting the src attribute for the script tag, the browser will send the request, but only one request can be sent. As a result, the script tag cannot be reused. Therefore, the script tag must be removed after each operation. A global callback function is bound to the browser before sending a request. When the data request is successful, the callback function is called.

Summary

The two asynchronous data transmission methods are integrated to determine which method is selected based on dataType. Paste complete code

Var xyfAjax = {ajax: function (params) {params = params | |{}; params. cache = params. cache | false; if (! Params. url) {throw new Error ('invalid parameter ');} params. dataType = (params. dataType | 'json '). toLowerCase (); if (params. dataType = 'jsonp') {this. ajaxJSONP (params);} else if (params. dataType = 'json') {this. ajaxJSON (params );}}, /*** request through JSONP * @ param {[type]} params [description] * @ return {[type]} [description] */ajaxJSONP (params) {params. data = params. data ||{}; params. jsonp = params. jso Np | 'callback'; // sets the callback parameter name and parameter value passed to the backend. var callbackName = 'jsonp _ '+ (new Date ()). getTime (); params. data [params. jsonp] = callbackName; var formatedParams = this. formateParams (params. data, params. cache); // create a script tag and insert it into the page var head = document. getElementsByTagName ('head') [0]; var script = document. createElement ('script'); head. appendChild (script); // create the jsonp callback function window [callbackName] = function (json) {Head. removeChild (script); clearTimeout (script. timer); window [callbackName] = null; params. success & params. success (json) ;}; // sends the request script. src = (!! FormatedParams? Params. url + '? '+ FormatedParams: params. url); // to determine whether the request is successful, set timeout for processing if (params. time) {script. timer = setTimeout (function () {window [callbackName] = null; head. removeChild (script); params. error & params. error ({message: 'timeout'}) ;}, params. time );}}, /*** request in JSON format * @ param {[type]} params [description] * @ return {[type]} [description] */ajaxJSON (params) {params. type = (params. type | 'get '). toUpperCase (); Params. data = params. data ||{}; var formatedParams = this. formateParams (params. data, params. cache); var xhr; // create the XMLHttpRequest object if (window. XMLHttpRequest) {// non-IE6 xhr = new XMLHttpRequest ();} else {xhr = new ActiveXObject ('Microsoft. XMLHTTP ');} // Changes the asynchronous status and receives the response data xhr. onreadystatechange = function () {if (xhr. readyState = 4 & xhr. status = 200) {if (!! Params. success) {if (typeof xhr. responseText = 'string') {params. success (JSON. parse (xhr. responseText);} else {params. success (xhr. responseText) ;}} else {params. error & params. error (status) ;}} if (params. type = 'get') {// connect to the server xhr. open ('get ',(!! FormatedParams? Params. url + '? '+ FormatedParams: params. url), true); // send the request xhr. send (null);} else {// connect to the server xhr. open ('post', params. url, true); xhr. setRequestHeader ('content-type', 'application/x-www-form-urlencoded'); // send the request xhr. send (formatedParams );}}, /*** format the data ** @ param {Obj} data the data to be formatted * @ param {Boolean} Does isCache Add a random parameter * @ return {String} to the returned String */formateParams: function (data, isCache) {var arr = []; for (var name in data) {arr. push (encodeURIComponent (name) + '=' + encodeURIComponent (data [name]);} if (isCache) {arr. push ('v = '+ (new Date ()). getTime ();} return arr. join ('&') ;}} xyfAjax. ajax ({url: 'http: // www.xieyufei.com ', type: 'get', // or post dataType: 'json', // or jsonp data: {name: 'xyf'}, success: function (data) {console. log (data )}})

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.