TAT.yukin 使用 HTML5 跨域共享特性解决 AJAX 跨域数据同步问题
In 未分类 on 2012年11月05日 by view: 20,905
5

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:*表示允许所有的域名跨域访问。


如果需要读取读取 cookie:
需要配置参数:Access-Control-Allow-Credentials:true
同时在 xhr 发起请求的时候设置参数 withCredentials 为 true:
var xhr = new XMLHttpRequest();
xhr.open();
xhr.withCredentials = true; //这个放在 xhr.open 后面执行,否则有些浏览器部分版本会异常,导致设置无效。

示例代码:
php:

JS:

原创文章转载请注明:

转载自AlloyTeam:http://www.alloyteam.com/2012/11/html5-cors/

  1. 秦梦妍 2016 年 3 月 6 日

    [不活了]

  2. s 2016 年 1 月 25 日

    ios 始终报 Failed to load resource: The network connection was lost.

  3. jackstraw 2014 年 9 月 2 日

    这样子 cookie 还是不能跨域

  4. cors, xhr2,跨域,跨域共享,html5,Cross-Origin Resource Sharing | Tencent AlloyTeam – 码农们的博客 2013 年 9 月 25 日

    […] 通过 cors, xhr2, 跨域, 跨域共享,html5,Cross-Origin Resource Sharing | Tencent AlloyTeam. var ujian_config = { 'num':5, 'showType':2, 'bgColor':"", 'mouseoverColor':"#E6F3DE", 'textColor':"#333333", 'hoverTextColor':"#333333", 'borderColor':"#dddddd", 'picSize':96, 'target':0, 'textHeight':60, 'defaultPic':"", 'itemTitle':" 云计算分析你可能喜欢:" } […]

  5. waylon 2012 年 11 月 30 日

    jquey1.5.1+, ajax 提供了这个配置~~
    xhrFields(added 1.5.1)Map
    A map of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed.

    $.ajax({
    url: a_cross_domain_url,
    xhrFields: {
    withCredentials: true
    }
    });

发表评论到 jackstraw