Native JS encapsulates Ajax plug-ins (same domain, jsonp cross-domain), ajaxjsonp

Source: Internet
Author: User
Tags subdomain name

Native JS encapsulates Ajax plug-ins (same domain, jsonp cross-domain), ajaxjsonp

A question is thrown out. What is the degree of familiarity with native JS?

Recently I have been doing exercises familiar with native JS...

It is feasible to use native Js to encapsulate an Ajax plug-in, introduce a general project, and transmit data... Let's talk about the train of thought. If there are any errors, I hope to correct them. ^_^

I. Create XHR objects at the Ajax Core

The core of Ajax technology is the XMLHttpRequest object (XHR). IE5 is the first browser to introduce XHR objects, while the XHR objects in IE5 are implemented through an ActiveX object in the MSXML library, therefore, there may be three versions in IE: MSXML2.XMLHttp and MSXML2.XMLHttp. 3.0 and MSXML2.XMLHttp. 6.0. Therefore, when creating an XHR object, use the Compatibility Statement:

createXHR:function(){ if(typeof XMLHttpRequest!='undefined'){ return new XMLHttpRequest(); }else if(typeof ActiveXObject!='undefined'){ if(typeof arguments.callee.activeXString!='string'){  var versions=["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"],i,len;  for(i=0,len=versions.length;i<len;i++){  try{   new ActiveXObject(versions[i]);   arguments.callee.activeXString=versions[i];   break;  }catch(ex){  }  }  return new ActiveXObject(arguments.callee.activeXString);  }else{  throw new Error("No XHR object available."); }}

Ii. Main method attributes of XHR

Method:

Open () method: three parameters are accepted, including the type of the request to be sent, the request URL, and whether to send a Boolean value asynchronously.

Send () method: data to be sent as the request body. If you do not need to send data through the request body, null must be input.

Abort () method: call to cancel an asynchronous request before receiving the response.

Attribute:

ResponseText: The text returned as the response body.

Status: the HTTP status of the response.

StatusText: HTTP status description

ReadyState: indicates the current active stage of the Request/response process.

Values:

0: not initialized. The open () method has not been called.

1: Start. The open () method has been called, but the send () method has not been called.

2: Send. The send () method has been called, but the response is not received.

3: receive. Some response data has been received

4: complete. All response data has been received and can be used on the client.

The onreadystatechange event handler function in this example:

Var complete = function () {if (xhr. readyState = 4) {if (xhr. status >=200 & xhr. status <300) | xhr. status = 304) {if (params. success) {params. success (xhr. responseText); // execute the success function specified when calling ajax} else {if (params. fail) {params. fail (); // The fail function specified when ajax is called} else {throw new Error ("Request was unsucessful:" + xhr. status );}}}}

Note: You must specify the onreadystatechange event handler before calling the open () method to ensure cross-browser compatibility.

3. Send requests in the same domain

① GET request

The most common request type, which is often used to query certain information. The query string parameter is appended to the end of the URL to send the information to the server. For a get Method Request, you must use encodeURIComponent () to encode each parameter name and value in the query string, and all name-value pairs must be separated.

Request Method:

If (this. config. type = "GET") | (this. config. type = "get") {for (var item in this. config. data) {this. config. url = addURLParam (this. config. url, item, this. config. data [item]); // use encodeURIComponent () for encoding} xhr. onreadystatechange = complete; xhr. open (this. config. type, this. config. url, this. config. async); xhr. send (null );}

② POST request

It is usually used to send data that should be saved to the server. the post request should submit the data as the request body. Here we will simulate form submission. Set the Content-Type header information to application/x-www-form-urlencoded; charset = UTF-8.

Serialization function:

 function serialize(data){  var val="";  var str="";  for(var item in data){   str=item+"="+data[item];   val+=str+'&';  }  return val.slice(0,val.length-1); }

Request Method:

if(this.config.type=="POST"||this.config.type=="post"){  xhr.addEventListener('readystatechange',complete);  xhr.open(this.config.type,this.config.url,this.config.async);  if(params.contentType){   this.config.contentType=params.contentType;   }  xhr.setRequestHeader("Content-Type",this.config.contentType);  xhr.send(serialize(this.config.data));}

There are some differences between the two requests:

① The GET request writes the parameter data to the URL, which can be seen in the URL but not in the POST. Therefore, the GET is insecure and the POST is safer.

② The data volume transmitted by GET is small and cannot exceed 2 kb. The amount of data transmitted by POST is large, which is not restricted by default.

③ The GET server uses Request. QueryString to obtain the variable value, and the POST Server uses Request. From to obtain the variable value.

④ GET adds data to the URL and transmits it to the server. Usually, ?, Each data parameter in the following parameters appears in the form of "name = value". A connector is used to distinguish between parameters. POST data is stored in the HTTP body. There are more than one organization method, including the & Link Method and the separator method. It is convenient to hide parameters and transmit a large amount of data.

Iv. jsonp cross-origin sending request

First, what is the situation of CORS?

Composition of a domain name:

Http: // www. abc.com: 8080/scripts/AjaxPlugin. js

Resource Address requested by the Protocol subdomain name master domain name port number

~ If any of the protocols, subdomains, primary domain names, and port numbers is different.

~ Different domains request resources from each other, even if it is "cross-origin ".

All browsers comply with the same origin policy. This policy ensures that the dynamic scripts of one source cannot read or operate on http responses and cookies of other sources, which isolates the browser from different sources, prevents them from performing operations on each other. The so-called same source means that the Protocol, domain name, and port are consistent. The browser blocks ajax requests from different sources.

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. However, jsonp supports only get requests across domains.

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.

Jsonp cross-domain mainly needs to consider three issues:

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;
Because the code is a little long, let's put a timer Code. For the complete code, see AjaxPlugin.

// Timeout processing if (params. time) {scriptTag. timer = setTimeout (function () {head. removeChild (scriptTag); params. fail & params. fail ({message: "over time"}); window [cbName] = null ;}, params. time );}

The above is all the content of this article, hoping to help you learn.

Detailed analysis and use of plug-ins see: https://github.com/LuckyWinty/AjaxPlugin

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.