Detailed Description: Custom ajax supports cross-origin component encapsulation and ajax

Source: Internet
Author: User

Detailed Description: Custom ajax supports cross-origin component encapsulation and ajax

Class. create () Analysis

Create class inheritance like prototype

var Class = {  create: function () {    var c = function () {      this.request.apply(this, arguments);    }    for (var i = 0, il = arguments.length, it; i < il; i++) {      it = arguments[i];      if (it == null) continue;      Object.extend(c.prototype, it);    }    return c;  }};Object.extend = function (tObj, sObj) {   for (var o in sObj) {    tObj[o] = sObj[o];  }  return tObj;};

Ajax definition: ZIP_Ajax = Class. create ();

The create method returns a constructor request, which is equivalent to var ZIP_Ajax = function () {this. request. apply (this, arguments) ;}; a constructor is executed in the function using the object impersonating method, which is equivalent to handing over the constructor task to the request method. here this. request is the method of the ZIP_Ajax instance, and this points to the ZIP_Ajax instance. this points to the ZIP_Ajax instance after apply, and finally points this to the ZIP_Ajax class based on the new keyword. With the definition of ZIP_Ajax class, you can then define its method:

XMLHttpRequest details:

XMLHttpRequest is not a technology, but an object built into mainstream browsers that can fully access the http protocol. Most traditional http requests submit http requests based on form, and then return a form. The biggest advantage of XMLHttpRequest supporting synchronous requests is that it supports asynchronous transmission to receive data. Creating an ajax request actually instantiates an XMLHttpRequest object. Briefly introduce the main events and methods:

Readystatechange event:

When XMLHttpRequest sends an http request, a readystatechange event is triggered. The event returns five values, 0, 1, and 2, indicating creating XMLHttpRequest, completing XMLHttpRequest initialization, and sending a request, 3 indicates that the response is not over (that is, only the response header data is received). 4. The response is complete.

The returned status indicates the status code returned by the server:

200 indicates that data is returned successfully, 301 indicates permanent redirection, 302 indicates temporary redirection (Insecure), 304 indicates that the cached data read by 400 indicates that the request has a syntax error, and 403 indicates that the server rejects the request, 404 indicates that the requested webpage resource does not exist. 405 indicates that the server cannot be found at the specified location, 408 indicates that the request times out, 500 indicates that the server has an internal error, and 505 indicates that the server does not support the http protocol version of the request.

500-indicates success,-Indicates redirection,-indicates that the request content or format or the request body is too large, leading to an error. + indicates an internal server error.

Open method:

The three parameters of open receiving are request type (get, post, head, etc.), url, synchronous or asynchronous.

Send method:

When the request is ready, the send method is triggered. The sent content is the request data (if it is a get request, the parameter is null;

After the request is successful, the success custom method is executed. Its parameter is the returned data;

Ajax cross-origin:

What is cross-origin?

If the two sites www.a.com want to request data from www. B .com, the cross-domain problem is caused by inconsistent domain names. Even if the domain name is the same, if the port is different, there will be a cross-origin problem (this is the reason that js can only stand ). Determine whether cross-origin is only through window. location. protocol + window. location. host to judge such as http://www.baidu.com.

How can js solve cross-origin problems?

1. document. domain + iframe

For requests with the same primary domain and different subdomains, the domain name + iframe can be used as a solution. The specific idea is that there are two different AB files under the domain name www.a.com/a.html

And hi.a.com/ B .html, we can add document.domain= "a.com" to the two HTML files, and then create an iframe in file a to control the contentDocument of iframe, so that the two files can be connected. Example:

In the.html file on www.a.com

Document. domain = "a.com"; var selfFrame = document. createElement ("iframe"); selfFrame. src = "http://hi.a.com/ B .html"; selfFrame. style. display = "none"; document. body. appendChild (selfFrame); selfFrame. onload = function () {var doc = selfFrame. contentDocument | selfframe.content%w.doc ument; // The B .html operation permission alert (doc. getElementById ("OK _ B "). innerHTML (); // perform operations on elements in file B}

In the B .html file on hi.a.com

Document. domain = "a.com ";

Problem:

1. Security: When a website (hi.a.com) is attacked, another website (www.a.com) may cause a security vulnerability. 2. If multiple iframe is introduced to a page, you must set the same domain to operate all iframe operations.

2. dynamically create a script (the legendary jsonp method)

By default, the browser prohibits cross-origin access, but does not prohibit reference js files of other domain names in the page, and can execute methods such as introducing js files, based on this, we can create a script node to implement full cross-origin communication. The implementation steps are as follows:

A. A script is dynamically loaded on the request initiator page. The script url points to the receiver's background. The javascript method returned by this address is executed by the initiator. parameters can be passed through the url and only get parameters can be submitted.

B. Call the cross-origin js method for callback processing (jsonp) when loading the script ).

Example:

Initiator

Function uploadScript (options) {var head = document. getElementsByTagName ("head") [0]; var script = document. createElement ("script"); script. type = "text/javasctipt"; options. src + = '? Callback = '+ options. callback; script. src = options. src; head. insertBefore (script, head. firstChild);} function callback (data) {} window. onload = function () {// call uploadScript ({src: "http://e.com/xxx/main.ashx", callback: callback })}

Receiver:

The receiver only needs to return an execution function, which is the callback in the request and assigned a parameter.

3. Use postMessage of html5:

One of the new html5 features is cross-document message transmission, which is now supported and used by most browsers (including ie8 +). It supports real-time web-based message transmission without cross-origin issues. PostMessage is generally used with iframe.

Example:

Parent page:

<Iframe id = "myPost" src = "http // www.a.com/main.html"> </iframe> window. onload = function () {document. getElementById ("myPost "). contentWindow. postMessage ("show me", "http://www.a.com") // The second parameter indicates that the data is sent to the document that fits the domain name} a.com/main.htmlpage: Too Many addeventlistener ("message", function (event) {if (event. origin. indexOf ("a.com")>-1) {document. getElementById ("textArea "). innerHTML = event. data ;}, false) <body> <div> <span id = "textArea"> </span> </div> </body>

In this example, the textArea section of the main.html page will display "show me" after the parent page is complete.

Ajax method encapsulation code:

ZIP_Ajax.prototype = {request: function (url options) {this. options = options; if (options. method = "jsonp") {// return this for cross-origin requests. jsonp ();} var httpRequest = this. http (); options = Object. extend ({method: 'get', async: true}, options ||{}); if (options. method = "get") {url + = (url. indexOf ('? ') =-1? '? ':' & ') + Options. data; options. data = null;} httpRequest. open (options. method, url, options. async); if (options. method = 'post') {httpRequest. setRequestHeader ('content-type', 'application/x-www-form-urlencoded; charset = UTF-8 ');} httpRequest. onreadystatechange = this. _ onStateChange. bind (this, httpRequest, url, options); httpRequest. send (options. data | null); // If the get request is null, return httpRequest;}, j Sonp: function () {jsonp_str = 'jsonp _ '+ new Date (). getTime (); eval (jsonp_str + '=' + this. options. callback + ';'); this. options. url + = '? Callback = '+ jsonp_str; for (var I in this. options. data) {this. options. url + = '&' + I + '=' + this. options. data [I];} var doc_head = document. getElementsByTagName ("head") [0], doc_js = document. createElement ("script"), doc_js.src = this. options. url; doc_js.onload = doc_js.onreadystatechange = function () {if (! This. readyState | this. readyState = "loaded" | this. readyState = "complete") {// clear JS doc_head.removeChild (doc_js) ;}} doc_head.appendChild (doc_js) ;}, http: function () {// determine whether xmlHttp if (window. XMLHttpRequest) {return new XMLHttpRequest ();} else {try {return new ActiveXObject ('msxml2. XMLHTTP ')} catch (e) {try {return new ActiveXObject ('Microsoft. XMLHTTP ') ;}catch (e) {return false ;}}}}, _ OnStateChange: function (http, url, options) {if (http. readyState = 4) {http. onreadystatechange = function () {}; // reset the event to null var s = http. status; if (typeof (s) = 'number' & s> 200 & s <300) {if (typeof (options. success )! = 'Function') return; var format = http; if (typeof (options. format) = 'string') {// determine the request data format switch (options. format) {case 'text': format = http. responseText; break; case 'json': try {format = eval ('+ http. responseText + ');} catch (e) {if (window. console & console. error) console. error (e);} break; case 'xml': format = http. responseXML; break;} options. success (format); // successful callback} else {// post-processing if (window. closed) return; if (typeof (options. failure) = 'function') {var error = {status: http. status, statusText: http. statusText} // determines whether the network is disconnected or the server cannot be requested if (http. readyState = 4 & (http. status = 0 | http. status = 12030) {// error. status =-1;} options. failure (error );}}}}};

Usage:

Ajax call example:

Var myAjax = new ZIP_Ajax ("http://www.a.com/you.php", {method: "get", data: "key = 123456 & name = yuchao", format: "json", success: function (data ){......}}) cross-origin request Call example: var jsonp = new ZIP_Ajax ("http://www.a.com/you.php", {method: "jsonp", data: {key: "123456", name: "yuchao"}, callback: function (data ){......}})

 

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.