Native JS encapsulated Ajax plug-in (same domain &&jsonp cross-domain)

Source: Internet
Author: User
Tags string back

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

Recently are doing the native JS familiar practice ...

With the native JS encapsulated an AJAX plug-in, the introduction of general projects, data transmission, the feeling is still feasible ... Simply say the idea, if there is an incorrect place, but also look at the ^_^

First, Ajax core, create XHR object

The core of Ajax is the XMLHttpRequest object (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 creating XHR objects, use compatibility notation:

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

Second, the Main method attribute of XHR

Method:

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

Send () method: The data to be sent as the request principal, if you do not need to send data through the request principal, you must pass in NULL

Abort () method: Called before the response is received to cancel an asynchronous request.

Property:

ResponseText: The text to be returned as the response body.

Status: HTTP status of the response

Statustext:http Status Description

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

The values were:

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 has not been received.

3: Receive. Part of the response data has been accepted

4: Complete. All response data has been accepted and can already be used on the client.

In this example, the onReadyStateChange event handler function:

123456789101112131415 var complete=function(){    if(xhr.readyState==4){     if((xhr.status>=200&&xhr.status<300)||xhr.status==304){        if(params.success){         params.success(xhr.responseText);//执行调用ajax时指定的success函数         }    }else{        if(params.fail){        params.fail();//执行调用ajax时指定的fail函数       }else{        throw new Error("Request was unsucessful:"+xhr.status);       }    }    }}

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

Third, the same domain send the request

①get Request

The most common type of request, often used to query some 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 needs to be noted that each parameter name and value in the query string must be encoded using encodeURIComponent (), and all name-value pairs must be separated by the & number.

Request Method:

12345678 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]);//使用encodeURIComponent()进行编码    }   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 principal of the request. This will mimic the form submission. Content-type header information will be set to application/x-www-form-urlencoded; Charset=utf-8.

Serialization functions:

    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 between the two requests:

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

The amount of data transmitted by ②get is small and cannot be greater than 2KB. Post transmits a large amount of data, which is generally not restricted by default.

③get server side with Request.QueryString to get the value of the variable, the post server side with Request.from to obtain.

④get add data to the URL to be passed to the server, usually using one? , each data parameter in the following parameter appears as a "name = value", and the parameter and parameter are distinguished by a connector &. Post data is placed in the HTTP body, it is organized in more than one way, there are & links, there is also a delimiter way. Can hide the parameters, the delivery of large numbers of data, more convenient.

Iii. Jsonp cross-domain send request

First, cross-domain is God horse situation?

The composition of a domain name:

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

Protocol subdomain primary Domain name Port number Request resource address

~ When any of the protocols, subdomains, primary domain names, or port numbers are different, they are counted as distinct domains.

~ Different domains request resources from each other and are counted as "cross-domain".

All browsers adhere to the same-origin policy, which ensures that one source's dynamic scripts cannot read or manipulate HTTP responses and cookies from other sources, which allows the browser to isolate content from different sources and prevent them from interacting with each other. The so-called homology refers to the agreement, the domain name and the port are consistent situation. The browser blocks AJAX requests for non-homologous content.

JSONP (JSON with Padding) is a cross-domain request method. The main principle is to take advantage of the script tag can cross-domain request characteristics, by its SRC attribute to send the request to the server, the server returns JS code, the Web side accept the response, and then directly executed, and the script tag refers to the external file is the same principle. However, JSONP only supports get requests across domains.

JSONP consists of two parts: the callback function and the data, the callback function is usually controlled by the Web page, as a parameter to the server side, the server side of the function and data are spelled into a string back.

There are three main issues to consider in Jsonp cross-domain:

1, because the SRC attribute of the script tag only works at the time of the first setting, which causes the script tag to not be reused, so it is removed after each completion of the operation;

2, Jsonp This request method, the parameters still need to encode;

3, if not set timeout, will not know whether the request is a success or failure; Because the code is a bit long, put a timer code bar, complete code see Ajaxplugin
12345678 //超时处理if(params.time){   scriptTag.timer=setTimeout(function(){       head.removeChild(scriptTag);       params.fail&&params.fail({message:"over time"});       window[cbName]=null;    },params.time);}

Plugin detailed analysis and use method see: Https://github.com/LuckyWinty/AjaxPlugin

Learn about post cross-domain demand points here Tags:JS

Native JS encapsulated Ajax plug-in (same domain &&jsonp cross-domain)

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.