ajax通过设置Access-Control-Allow-Origin来实现跨域访问

[在被请求的Response header中加入]

// 指定允许其他域名访问(*代表所有域名)
header('Access-Control-Allow-Origin:*');
// 响应类型
header('Access-Control-Allow-Methods:POST');
// 响应头设置
header('Access-Control-Allow-Headers:x-requested-with,content-type');

[例]

<div id="show"></div>  
<script type="text/javascript">  
$.post("http://www.server.com/server.php",{uid:"21"}).done(function(data){  
    $("#show").html(data.name);  
  });  
</script> 
<?php
$ret = ['uid' => isset($_POST['uid'])? $_POST['uid'] : ''];

header('content-type:application:json;charset=utf8');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');

echo json_encode($ret);
?>
posted @ 2016-06-20 10:14  yudis  阅读(992)  评论(0编辑  收藏  举报