HTML5 AJAX跨域請求


HTML5新的標准中,增加了” Cross-Origin Resource Sharing”特性,這個特性的出現使得跨域通信只需通過配置http協議頭來即可解決。

Cross-Origin Resource Sharing 詳細解釋見:
http://dvcs.w3.org/hg/cors/raw-file/tip/Overview.html

Cross-Origin Resource Sharing實現的最重要的一點就是對參數” Access-Control-Allow-Origin”的配置,即通過 次參數檢查該跨域請求是否可以被通過。
如:Access-Control-Allow-Origin:http://a.com表示允許a.com下的域名跨域訪問;
Access-Control-Allow-Origin:*表示允許所有的域名跨域訪問。

如果需要讀取讀取cookie:
需要配置參數:Access-Control-Allow-Credentials:true
同時在xhr發起請求的時候設置參數withCredentials為true:
var xhr = new XMLHttpRequest();
xhr.open();
xhr.withCredentials = true; //這個放在xhr.open后面執行,否則有些瀏覽器部分版本會異常,導致設置無效。

JS:

varxhr =newXMLHttpRequest(); ; 
xhr.open('GET','http: //b.com/cros/ajax.php',true);
xhr.withCredentials =true;
xhr.onload =function() {          
  alert(xhr.response);//reposHTML;
};  
xhr.onerror =function() {
 alert('error making the request.');
};
xhr.send();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM