跨域解决方案CORS使用方法

CORS(Cross-Origin Resource Sharing), 目前CORS还处于w3c的草案,它定义了跨域访问时服务器和客户端之间如何通信。他的原理是通过定义HTTP头部的信息,来让客户端和服务器互相确认,从而决定是否相应本次请求。

兼容性: IE10+  chrome21+  firefox21+  safari5.1+  opera12.1+ (IE8, 9中使用XDomainRequest)

    详见 http://caniuse.com/cors , 可通过(new XMLHttpRequest).withCredentials !== undefined判断

客户端:

 1 function compatibleCORS(method, url) {
 2     var xhr = new XMLHttpRequest();
 3     if (xhr.withCredentials !== undefined) {
 4         xhr.open(method, url, true);
 5     } else if (typeof XDomainRequest !== "undefined") {
 6         //XDomainRequest是IE用于支持CORS请求的对象
 7         xhr = new XDomainRequest();
 8         xhr.open(method, url);
 9     } else {
10         xhr = null;
11     }
12     return xhr; 
13 }
14 
15 var xhr = compatibleCORS('GET', "your url");
16 if (!xhr) {
17     throw new Erorr("CORS不被支持");
18 }

服务端: 

  通过设置http响应头Access-Control-Allow-Origin: www.xxx.com(这里可以是*, 代表接受任意域名的跨域申请, 但为了安全策略, 一般情况下不要这样做)

  这样客户端的代码就能得到响应

 

posted @ 2014-07-29 18:10  yedeying  阅读(2159)  评论(0编辑  收藏  举报