This article mainly gives you a detailed analysis of the knowledge points related to custom ajax support for cross-domain component encapsulation. Friends who are interested in this can refer to it and hope to help everyone.
Class.create() analysis
Imitate prototype to create class inheritance
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); }; executed inside the function by impersonating the object. The process of a construction is equivalent to handing over the constructor task to the request method. This.request here is the method of the ZIP_Ajax instance, and this points to the ZIP_Ajax instance. This after apply points to ZIP_Ajax. Finally, according to new The keyword will actually point this to the ZIP_Ajax class. With the definition of the class ZIP_Ajax, you can then define its method:
XMLHttpRequest Detailed explanation:
XMLHttpRequest is not a technology but a function built into mainstream browsers. Full access to http protocol objects. Most traditional http requests are based on form submission and request http, and then return a form. While XMLHttpRequest supports synchronous requests, the biggest advantage is that it supports asynchronous transmission and reception of data. Creating a new ajax request is actually instantiating an XMLHttpRequest object. A brief introduction to the main events and methods:
readystatechange event:
When XMLHttpRequest sends an http request, a readystatechange event will be triggered. The event returns five values. 0, 1, and 2 respectively represent the creation of XMLHttpRequest, completion of XMLHttpRequest initialization, and sending the request. 3 represents that the response has not ended (that is, only the response header data is received). 4 is the real response to the complete response.
The returned status status indicates the status code returned by the server:
The commonly used ones are 200 indicating successful return of data, 301 permanent redirection, and 302 temporary redirection (not Security) 304 reads cached data, 400 indicates a syntax error in the request, 403 indicates that the server rejects the request, 404 indicates that the requested web page resource does not exist, 405 cannot find the server at the specified location, 408 indicates that the request has timed out, 500 indicates an internal server error, and 505 indicates that the server The requested http protocol version is not supported.
200-300 indicates success, 300-400 indicates redirection, 400-500 indicates that the request content or format or the request body is too large causing an error, 500+ indicates an internal server error
open method:
open receives three parameters: request type (get, post, head, etc.), url, synchronous or asynchronous
send method:
When the request is ready, the send method will be triggered, and the content sent is the requested data (if it is a get request, the parameter is null;
After the request is successful, success will be executed Custom method whose parameters are return data;
ajax cross-domain:
What is cross-domain?
If two sites When www.a.com wants to request data from www.b.com, cross-domain problems occur due to inconsistent domain names. Even if the domain names are the same, if the ports are different, there will be cross-domain problems (for this reason, js can only stand by and watch. ). To determine whether it is cross-domain, just use window.location.protocol+window.location.host. For example, http://www.baidu.com.
js has several ways to solve cross-domain problems. Solution?
1. document.domain+iframe
For requests with the same main domain but different subdomains, 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=" to the two html files a.com", and then create an iframe in the a file to control the contentDocument of the iframe, so that the two files can communicate. For example:
a on www.a.com. In the html file
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.contentWindow.document;//得到操作b.html权限 alert(doc.getElementById("ok_b").innerHTML());//具体操作b文件中元素 }
In the b.html file on hi.a.com
document.domain="a.com";
Problem:
1. Security. When one site (hi.a.com) is attacked, another site (www.a.com) will cause security holes. 2. If multiple pages are introduced. If you want to be able to operate all iframes, you must set the same domain.
2. Dynamically create scripts (the legendary jsonp method)
Browsers prohibit cross-domain access by default. , but it is not prohibited to reference js files of other domain names in the page, and methods introduced in js files can be executed. Based on this, we can achieve complete cross-domain communication by creating script node methods. The implementation steps are:
a. Dynamically load a script on the request initiator page. The url of the script points to the receiver's backend. The javascript method returned by the address will be executed by the initiator. The url can pass parameters. And only supports get submission parameters.
b. When loading the script, call the cross-domain js method for callback processing (jsonp).
For 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(){//调用 uploadScript({src:"http://e.com/xxx/main.ashx",callback:callback}) }
Receiver:
The receiver only needs to return an execution function , the execution function is the callback in the request and assigns parameters.
3. Use postMessage of html5:
One of the new features of html5 is cross-document message transmission, which is now supported and used by most browsers (including ie8+) , which supports web-based real-time messaging and has no cross-domain issues. postMessage is generally used with iframe.
举例如下:
父页面:
window.onload=function(){ document.getElementById("myPost").contentWindow.postMessage("显示我","http://www.a.com") //第二个参数表示确保数据发送给适合域名的文档 } a.com/main.html页面: window.addEventListener("message",function(event){ if(event.origin.indexOf("a.com")>-1){ document.getElementById("textArea").innerHTML=event.data; } },false)
这样在父页面加载完成后main.html页面的textArea部分就会显示"显示我"三个字
ajax方法封装code:
ZIP_Ajax.prototype={ request:function(url options){ this.options=options; if(options.method=="jsonp"){//跨域请求 return this.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);//get请求情况下data为null return httpRequest; }, jsonp: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"){ //清除JS doc_head.removeChild(doc_js); } } doc_head.appendChild(doc_js); }, http:function(){//判断是否支持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(){};//重置事件为空 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'){//判断请求数据格式 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);//成功回调 } else {//请求出问题后处理 if (window.closed) return; if (typeof (options.failure) == 'function') { var error = { status: http.status, statusText: http.statusText } // 判断是否是网络断线或者根本就请求不到服务器 if (http.readyState == 4 && (http.status == 0 || http.status == 12030)) { // 是 error.status = -1; } options.failure(error); } } } } };
使用方法:
ajax调用举例:
var myAjax=new ZIP_Ajax("http://www.a.com/you.php",{ method:"get", data:"key=123456&name=yuchao", format:"json", success:function(data){ ...... } }) 跨域请求调用举例: var jsonp=new ZIP_Ajax("http://www.a.com/you.php",{ method:"jsonp", data:{key:"123456",name:"yuchao"}, callback:function(data){ ...... } })
相关推荐:
JS组件系列--组件封装深入:使用jquery data()和html 5 data-*属性初始化组件_html/css_WEB-ITnose
The above is the detailed content of Detailed explanation of custom ajax support for cross-domain component encapsulation. For more information, please follow other related articles on the PHP Chinese website!