码迷,mamicode.com
首页 > Web开发 > 详细

HTML5 AJAX跨域请求

时间:2018-01-04 16:23:28      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:xhr   ror   har   重要   允许   repo   cross   否则   详细   

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();

HTML5 AJAX跨域请求

标签:xhr   ror   har   重要   允许   repo   cross   否则   详细   

原文地址:https://www.cnblogs.com/liubingboke/p/8193475.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!