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();
posted @ 2018-01-04 15:03  刘兵博客  阅读(3149)  评论(0编辑  收藏  举报