服务端通过设置 响应头允许其他域名跨域访问数据

设置响应头:

#允许跨域的域,*代表所有域都接收

Access-Control-Allow-Origin: http://foo.example 

#允许跨域执行的方法

Access-Control-Allow-Methods: POST, GET, OPTIONS

#允许跨域设置的头信息

Access-Control-Allow-Headers: X-PINGOTHER

以下是nginx的方法
if ($request_method = 'OPTIONS') {
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Credentials true;
        add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        return 200;
    }
     if ($request_method = 'POST') {

        add_header 'Access-Control-Allow-Origin' *;
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

     }

     if ($request_method = 'GET') {

        add_header 'Access-Control-Allow-Origin' *;
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

     }

javascript:调用实例

在dev.int.weishi.mobil 的nginx上设置以上配置,javascript页面所属网站是www.shareach.com,通过跨域Post调用dev.int.weishi.mobil 上的数据

调用代码是
postData:function(data,success){
    var accountUrl = "http://dev.int.weishi.mobi/web"+rpc.urlUser;
    var jsonuserinfo = $.toJSON(data);
    jQuery.ajax({
        type : 'POST',
        contentType : 'application/json',
        url : accountUrl,
        data : jsonuserinfo,
        dataType : 'json',
        success : function(data) {
            if (data.code == 0) {
                success(data.result);
            }else{
                alert(data.msg);
            }
        },
        error : function(data) {
            alert("error")
        }
    });
},

posted @ 2012-03-13 13:23  shareach  阅读(1723)  评论(0编辑  收藏  举报