使用HTML5 跨域共享特性解决AJAX跨域数据同步问题(转)
HTML 5以前的标准由于考虑到浏览器安全问题并不允许直接跨域通信,于是为了达到跨域通信的目的各种蛋疼的解决办法出现了,常用的有:jsonp、使用代理文件、地址栏hash等等,这些办法的出现在达到解决跨域问题的同时,也增加了前端页面的性能开销和维护成本。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:*表示允许所有的域名跨域访问。
http://www.imyukin.com/wp-content/uploads/2012/11/xhr2.png
http://www.imyukin.com/wp-content/uploads/2012/11/header.png
如果需要读取读取cookie:
需要配置参数:Access-Control-Allow-Credentials:true
同时在xhr发起请求的时候设置参数withCredentials为true:
var xhr = new XMLHttpRequest();
xhr.open();
xhr.withCredentials = true; //这个放在xhr.open后面执行,否则有些浏览器部分版本会异常,导致设置无效。
示例代码:
php:
<div style=""><div style="" class="syntaxhighlighterphp">php<div style="margin: 0px !important; padding: 0px 0.5em 0px 1em !important; height: auto !important; font-size: 1em !important; border-top-width: 0px !important; border-top-left-radius: 0px !important; border-top-right-radius: 0px !important; border-bottom-right-radius: 0px !important; border-bottom-left-radius: 0px !important; background-image: none !important; border-right-width: 3px !important; border-bottom-width: 0px !important; border-left-width: 0px !important; border-right-style: solid !important; border-right-color: #76a2ff !important; float: none !important; line-height: 1.1em !important; overflow: visible !important; text-align: right !important; vertical-align: baseline !important; width: auto !important; white-space: pre !important;" class="line number1 index0 alt2">1
页:
[1]