Ajax principles and encapsulation details, Ajax principles encapsulation details

Source: Internet
Author: User

Ajax principles and encapsulation details, Ajax principles encapsulation details

Ajax is used every day. The jquery library is well-encapsulated and easy to use. Let's take a look at its internal principles and manually encapsulate an Ajax library.

For more information about ajax encapsulation and data processing, see Shanghai shangxue's "Ajax in ajax + Jq encapsulation" and "ajax + json data processing".

I, Principle

Four steps are required for sending native Ajax:
1) Create an Ajax object: XMLHttpRequest
2) Set Request Parameters: open (request parameter [get/post], url address, asynchronous or not [true/false])
3) set the callback function: onreadystateChange is used to process the returned data.
4) send request: send ()

// TODO Step 1: Create the ajax object var xhr = new XMLHttpRequest (); // TODO Step 2: Set the request parameter xhr. open ('get', '01. php', true); // TODO step3: Set the callback xhr. onreadystatechange = function () {// receives the returned data console. log (xhr. responseText); // responseText is used to receive the text of the background response} // TODO step4: send the request xhr. send ();
II, Encapsulation

The core idea of encapsulation is to regard the dynamically changed part as a parameter, and the unchanged part will be left there. In the above Code, the request method (get, post), request url, request parameter data, successful callback success, failure callback error, and so on, these parameters are dynamic changes, while creating Ajax objects XMLHttprequest, event listening onreadystatechange, etc. are fixed, so the first step is to determine the encapsulated parameters:

I, Encapsulation

The core idea of encapsulation is to regard the dynamically changed part as a parameter, and the unchanged part will be left there. In the above Code, the request method (get, post), request url, request parameter data, successful callback success, failure callback error, and so on, these parameters are dynamic changes, while creating Ajax objects XMLHttprequest, event listening onreadystatechange, etc. are fixed, so the first step is to determine the encapsulated parameters:

#. Url request address

#. Data Request data

#. Type request type

#. Successful callback of success

#. Error failure callback

#. BeforeSend call return false before sending to prevent sending

#. The callback for successful complete ajax requests will be executed at any time

 

Function ajax (option) {// default init var init = {type: 'get', async: true, url: '', success: function () {}, error: function () {}, data :{}, beforeSend: function () {console. log ('before sending... '); return false ;}}; // TODO step1: merging parameter for (k in option) {init [k] = option [k];} // TODO step2: parameter conversion var params = ''; for (k in init. data) {params + = '&' + k + '=' + init. data [k];} var xhr = new XMLHttpRequest (); // Type url // TODO step3: differentiate get and post, and pass the parameter var url = init. url + '? __= '+ New Date (). getTime (); // TODO step4: var flag = init. beforeSend (); if (! Flag) {return;} if (init. type. toLowerCase () = 'get') {url + = params; xhr. open (init. type, url, init. async); xhr. send ();} else {xhr. open (init. type, url, init. async); xhr. setRequestHeader ('content-type', 'application/x-www-form-urlencoded'); xhr. send (params. substr (1);} xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200) {init. success (xhr. responseText);} else {// error init. error ();}}}}

 

Here, we should note that the location of the get and post parameter passing methods is different. The get request must be directly spliced behind the url address, and the post request must pass the parameter in the send method, in addition, this is the request header setRequestHeader ('content-type', 'application/x-www-

Form-urlencoded '), so it must be differentiated during encapsulation.

Because there are too many parameters, you do not need to input many parameters each time, otherwise it will be very cumbersome to use. Therefore, we adopt the default parameter format. If you do not pass in, you use the default value. If you pass in, you use the user's parameter.

Iii. Example
ajax({    url: 'test.json',    data:{test:123,age:456},    //type:'post',    success: function (res) {        console.log(res);    }});

 

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.