ajax跨站请求的方案

前不久,项目中有一些地方需要在不同子域名直接跨站请求。
以下整理当时所查资料记录之,以备日后查阅。

方案一:

在请求的数据接口添加http响应头
1.header:Access-Control-Allow-Origin。
如果页面url是http://localhost/index.html,
那么php 作为数据请求接口 可以这样写:
仅允许localhost,header(‘Access-Control-Allow-Origin:http://localhost’);
允许所有:header(‘Access-Control-Allow-Origin:*’);
在http header响应头告知浏览器那些域名可以跨域。

方案二.jquery jsonp

$.ajax({
    url:request_url,
    dataType:'jsonp',
    data:'',
});

 

方案三.src引入外部资源,执行回调函数。

<script type="text/javascript">
function callback(data)
{
    alert(data.msg);
}
</script>
<script type="text/javascript" src="http://l.test.com/cross_domain/data.php"></script>

 

备注:
1.方案2,3原理是一样的.jquery也是通过引入外部资源执行callback回调函数,jsonp封装起来易于使用

2. 方案2,3请求的接口内容需要返回执行js函数的名称。

例如:

$callback = 'callback';
$a = array('errnum'=>'0' , 'msg'=>'success done');
echo $callback.'('.json_encode($a).')';

 

作者: 白金马桶

天道酬勤...

发表评论