您好,登錄后才能下訂單哦!
跨域?qū)崿F(xiàn)的方法有好多種:
JSONP
cores
document.domain
window.postMessage()
今天主要分析的是Cores的實(shí)現(xiàn)---------------------------------------------------------
cores---Cross-Orgin Resource Sharing,使用自定義的HTTP頭部,讓服務(wù)器聲明那些來源是可以通過瀏覽器訪問該服務(wù)器上的資源,從而決定請(qǐng)求是成功還是失敗。
客戶端:
<input type="button" value="測(cè)試開始" onclick="crossDomainRequest()"/> <div id="content"></div> <script> var content = document.getElementById('content'); function crossDomainRequest(){ content.innerHTML = '請(qǐng)求開始'; var url = 'http://——————————————————'; //創(chuàng)建ajax對(duì)象 if(window.XMLHttpRequest){ var xhr = new XMLHttpRequest(); }else{ var xhr = new ActiveXObject("Microsoft.XMLHTTP"); } if(xhr){ //建立連接 xhr.open('GET',url,true); //發(fā)送請(qǐng)求 xhr.send(); //預(yù)檢請(qǐng)求 xhr.setRequestHeader("POWERED-BY-MENGXIANHUI", "Approve"); xhr.setRequestHeader("Content-Type", "application/xml"); //帶驗(yàn)證信息請(qǐng)求 xhr.withCredentials = "true"; xhr.onreadystatechange = handler; }else{ content.innerHTML = '不能創(chuàng)建XHR對(duì)象'; } } function handler(xhr){ if(xhr.readyState == 4){ if(xhr.status == 200){ var response = xhr.responseText; content.innerHTML = "請(qǐng)求結(jié)果"+response; }else{ content.innerHTML = "不允許跨域請(qǐng)求"; } }else{ content.innerHTML = "readyState = "+xhr.readyState; } } </script>
服務(wù)器端:
protected void Page_Load(object sender, EventArgs e){ if (Request.HttpMethod.Equals("GET")) { Response.Write("這個(gè)頁面是用來測(cè)試跨域 POST 請(qǐng)求的,直接瀏覽意義不大。"); } else if (Request.HttpMethod.Equals("OPTIONS")) { //通知客戶端允許預(yù)檢請(qǐng)求。并設(shè)置緩存時(shí)間 Response.ClearContent(); Response.AddHeader("Access-Control-Allow-Origin", "你的地址"); Response.AddHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS"); Response.AddHeader("Access-Control-Allow-Headers", "POWERED-BY-MENGXIANHUI"); Response.AddHeader("Access-Control-Max-Age", "30"); //此過程無需返回?cái)?shù)據(jù) Response.End(); } else if (Request.HttpMethod.Equals("POST")) { if (Request.Headers["Origin"].Equals("你的地址")) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(Request.InputStream); Response.AddHeader("Access-Control-Allow-Origin", "http://你的地址"); Response.Write("您提交的數(shù)據(jù)是:<br/><br/>" + Server.HtmlEncode(doc.OuterXml)); } else { Response.Write("不允許你的網(wǎng)站請(qǐng)求。"); } } }
Access-Control-Allow-Origin //判斷來源
setRequestHeader() //預(yù)檢請(qǐng)求
withCredentials //帶驗(yàn)證信息請(qǐng)求
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。