Native JS encapsulates Ajax plug-ins (same domain, JSONP cross-domain) _javascript Tips

Source: Internet
Author: User
Tags script tag versions

Throw a question, in fact, the so-called familiar with the native JS, how the degree is familiar?

have been doing native JS familiar practice recently ...

With native JS encapsulated an AJAX plug-in, the introduction of general projects, transmission data, the feeling is still feasible ... Simply talk about the idea, if there is not the right place, also hope to correct the ^_^

One, Ajax core, create XHR objects

The core of Ajax technology is XMLHttpRequest objects (referred to as XHR), IE5 is the first browser to introduce XHR objects, and IE5 objects in XHR are implemented through an ActiveX object in the MSXML library, so there may be 3 versions in IE, namely Msxml2.xmlhttp, msxml2.xmlhttp.3.0 and msxml2.xmlhttp.6.0. So when you create a XHR object, you use the compatibility notation:

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.");
 }

Two, the Main method attribute of XHR

Method:

Open () Method: Accepts 3 parameters, the type of request to send, the URL requested, and whether the Boolean value is sent asynchronously

Send () method: Data to be sent as the body of the request, if no data is sent through the request body, you must pass in NULL

Abort () method: Called to cancel an asynchronous request before receiving a response.

Property:

ResponseText: The text that is returned as a response body.

Status: HTTP status of the response

Statustext:http Status Description

ReadyState: Represents the current active phase of a request/response process

Values are:

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

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

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

3: Receive. Partial response data has been accepted

4: Finished. All response data has been accepted and can already 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);//The Success function specified when invoking Ajax is executed
  }
 }else{
 if (params.fail) {
 params.fail ();//The FAIL function specified when the call to Ajax is performed
 }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.

Third, the same domain to send requests

①get Request

The most common type of request, often used to query for certain information. The information is sent to the server by appending the query's string parameter to the end of the URL. The Get method request should note that each parameter name and value in the query string must be encoded using encodeURIComponent (), and that all name-value pairs must be split by the & number.

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

Typically used to send data to the server that should be saved, the POST request should submit the data as the subject of the request. This will mimic the form submission. The Content-type header information will be set 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));
}

Some differences in two requests:

①get request to write parameter data to the URL, can be seen in the URL, and post is not visible, so get unsafe, post more secure.

The amount of data transmitted by the ②get is small and cannot be greater than 2KB. Post transfers have a large amount of data, and generally default to unrestricted.

③get server-side uses Request.QueryString to get the value of the variable, and the post server is request.from to get it.

④get adds data to the URL to pass to the server, usually using one? , each subsequent parameter is in the form of a "name = value", which is differentiated between parameters and parameters using a connector &. Post data is placed in the HTTP body, which is organized in more than one way, with & links and separator. Can hide parameters, transfer large numbers of data, more convenient.

Iv. JSONP send requests across domains

First of all, cross-domain is God horse situation?

The composition of a domain name:

http://www. Abc.com:8080/scripts/ajaxplugin.js

Protocol sub-domain principal domain name port number Request resource address

~ When any one of the protocols, subdomains, primary domain name, port number is not the same, it counts as different.

~ The request of resources between different domains counts as "Cross-domain".

All browsers adhere to the homology policy, which ensures that a source's dynamic script does not read or manipulate HTTP responses and cookies from other sources, which allows the browser to isolate content from different sources and prevent them from manipulating each other. The so-called homology refers to the agreement, domain name and port are consistent situation. Browsers block AJAX requests for content that is not homologous.

JSONP (JSON with Padding) is a Cross-domain request method. The main principle is to use the script tag can request the characteristics of Cross-domain, by its SRC attribute to send the request to the server, the server returned JS code, the Web page to accept the response, and then directly executed, this and through the script tag to refer to the external file is the same principle. However, JSONP supports only get requests across domains.

The JSONP is composed of two parts: callback function and data, the callback function is usually controlled by the web-end, which is sent to the server side as the parameter, and the server side returns the function and the data as a string.

There are three major issues that need to be considered for JSONP across domains:

1. Because the SRC attribute of the script tag only works at the first time, the script tag cannot be reused, so it is removed every time the operation is completed.

2, Jsonp This request method, the parameter still needs to encode;

3, if not set a timeout, you can not know whether the request is a success or failure;
Because the code is a bit long, put a timer code, complete code see Ajaxplugin

Timeout process
if (params.time) {
 scripttag.timer=settimeout (function () {
 head.removechild (scripttag);
 Params.fail&&params.fail ({message: ' Over time '});
 Window[cbname]=null;
 },params.time);

Detailed analysis of Plug-ins and the use of the method see: Https://github.com/LuckyWinty/AjaxPlugin

For more highlights, please click on the "Ajax cross-Domain technology summary" for in-depth study and research.

The above is the entire content of this article, I hope to help you learn.

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.