ajax 设置Access-Control-Allow-Origin实现跨域访问(post跨域),CORS

ajax跨域访问是一个老问题了,解决方法很多,比较常用的是JSONP方法,JSONP方法是一种非官方方法,而且这种方法只支持GET方式,不如POST方式安全。


即使使用jquery的jsonp方法,type设为POST,也会自动变为GET。


官方问题说明:

“script”: Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, “_=[TIMESTAMP]“, to the URL unless the cache option is set to true.Note: This will turn POSTs into GETs for remote-domain requests.


如果跨域使用POST方式,可以使用创建一个隐藏的iframe来实现,与ajax上传图片原理一样,但这样会比较麻烦。


因此,通过设置Access-Control-Allow-Origin来实现跨域访问比较简单。


例如:客户端的域名是www.client.com,而请求的域名是www.server.com

如果直接使用ajax访问,会有以下错误

XMLHttpRequest cannot load http://www.server.com/server.php. No ‘Access-Control-Allow-Origin’ header is present on the requested resource.Origin ‘http://www.client.com’ is therefore not allowed access.


在被请求的Response header中加入

  1. // 指定允许其他域名访问  
  2. header(’Access-Control-Allow-Origin:*’);  
  3. // 响应类型  
  4. header(’Access-Control-Allow-Methods:POST’);  
  5. // 响应头设置  
  6. header(’Access-Control-Allow-Headers:x-requested-with,content-type’);  
// 指定允许其他域名访问
header('Access-Control-Allow-Origin:*');
// 响应类型
header('Access-Control-Allow-Methods:POST');
// 响应头设置
header('Access-Control-Allow-Headers:x-requested-with,content-type');

就可以实现ajax POST跨域访问了。


代码如下:

client.html 路径:http://www.client.com/client.html

  1. <!DOCTYPE HTML PUBLIC ”-//W3C//DTD HTML 4.0 Transitional//EN”>  
  2. <html>  
  3.  <head>  
  4.   <meta http-equiv=“content-type” content=“text/html;charset=utf-8”>  
  5.   <title> 跨域测试 </title>  
  6.   <script src=“//code.jquery.com/jquery-1.11.3.min.js”></script>  
  7.  </head>  
  8.   
  9.  <body>  
  10.     <div id=“show”></div>  
  11.     <script type=“text/javascript”>  
  12.     $.post(“http://www.server.com/server.php”,{name:”fdipzone”,gender:”male”})  
  13.       .done(function(data){  
  14.         document.getElementById(“show”).innerHTML = data.name + ’ ’ + data.gender;  
  15.       });  
  16.     </script>  
  17.  </body>  
  18. </html>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
 <head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8">
  <title> 跨域测试 </title>
  <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
 </head>

 <body>
    <div id="show"></div>
    <script type="text/javascript">
    $.post("http://www.server.com/server.php",{name:"fdipzone",gender:"male"})
      .done(function(data){
        document.getElementById("show").innerHTML = data.name + ' ' + data.gender;
      });
    </script>
 </body>
</html>

server.php 路径:http://www.server.com/server.php

  1. <?php  
  2. ret</span><span>&nbsp;=&nbsp;</span><span class="keyword">array</span><span>(&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">'name'</span><span>&nbsp;=&gt;&nbsp;isset(</span><span class="vars">_POST[‘name’])? _POST</span><span>[</span><span class="string">'name'</span><span>]&nbsp;:&nbsp;</span><span class="string">''</span><span>,&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">'gender'</span><span>&nbsp;=&gt;&nbsp;isset(</span><span class="vars">_POST[‘gender’])? _POST</span><span>[</span><span class="string">'gender'</span><span>]&nbsp;:&nbsp;</span><span class="string">''</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>);&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;</span></li><li class="alt"><span>header(<span class="string">'content-type:application:json;charset=utf8'</span><span>);&nbsp;&nbsp;</span></span></li><li class=""><span>header(<span class="string">'Access-Control-Allow-Origin:*'</span><span>);&nbsp;&nbsp;</span></span></li><li class="alt"><span>header(<span class="string">'Access-Control-Allow-Methods:POST'</span><span>);&nbsp;&nbsp;</span></span></li><li class=""><span>header(<span class="string">'Access-Control-Allow-Headers:x-requested-with,content-type'</span><span>);&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;</span></li><li class=""><span><span class="func">echo</span><span>&nbsp;json_encode(</span><span class="vars">ret);  
  3. ?>  
<?php
$ret = array(
    'name' => isset($_POST['name'])? $_POST['name'] : '',
    'gender' => isset($_POST['gender'])? $_POST['gender'] : ''
);

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);
?>

Access-Control-Allow-Origin:* 表示允许任何域名跨域访问

如果需要指定某域名才允许跨域访问,只需把Access-Control-Allow-Origin:*改为Access-Control-Allow-Origin:允许的域名

例如:header(‘Access-Control-Allow-Origin:http://www.client.com‘);


如果需要设置多个域名允许访问,这里需要用php处理一下

例如允许 www.client.com 与 www.client2.com 可以跨域访问

server.php 修改为

  1. <?php  
  2. ret</span><span>&nbsp;=&nbsp;</span><span class="keyword">array</span><span>(&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">'name'</span><span>&nbsp;=&gt;&nbsp;isset(</span><span class="vars">_POST[‘name’])? _POST</span><span>[</span><span class="string">'name'</span><span>]&nbsp;:&nbsp;</span><span class="string">''</span><span>,&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">'gender'</span><span>&nbsp;=&gt;&nbsp;isset(</span><span class="vars">_POST[‘gender’])? _POST</span><span>[</span><span class="string">'gender'</span><span>]&nbsp;:&nbsp;</span><span class="string">''</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>);&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;</span></li><li class="alt"><span>header(<span class="string">'content-type:application:json;charset=utf8'</span><span>);&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;</span></li><li class="alt"><span><span class="vars">origin = isset(_SERVER</span><span>[</span><span class="string">'HTTP_ORIGIN'</span><span>])?&nbsp;</span><span class="vars">_SERVER[‘HTTP_ORIGIN’] : ;  
  3.   
  4. allow_origin</span><span>&nbsp;=&nbsp;</span><span class="keyword">array</span><span>(&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">'http://www.client.com'</span><span>,&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">'http://www.client2.com'</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>);&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;</span></li><li class=""><span><span class="keyword">if</span><span>(in_array(</span><span class="vars">originallow_origin</span><span>)){&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;header(<span class="string">'Access-Control-Allow-Origin:'</span><span>.</span><span class="vars">$origin</span><span>);&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;header(<span class="string">'Access-Control-Allow-Methods:POST'</span><span>);&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;header(<span class="string">'Access-Control-Allow-Headers:x-requested-with,content-type'</span><span>);&nbsp;&nbsp;</span></span></li><li class=""><span>}&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;</span></li><li class=""><span><span class="func">echo</span><span>&nbsp;json_encode(</span><span class="vars">ret);  
  5. ?>  
<?php
$ret = array(
    'name' => isset($_POST['name'])? $_POST['name'] : '',
    'gender' => isset($_POST['gender'])? $_POST['gender'] : ''
);

header('content-type:application:json;charset=utf8');

$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';

$allow_origin = array(
    'http://www.client.com',
    'http://www.client2.com'
);

if(in_array($origin, $allow_origin)){
    header('Access-Control-Allow-Origin:'.$origin);
    header('Access-Control-Allow-Methods:POST');
    header('Access-Control-Allow-Headers:x-requested-with,content-type');
}

echo json_encode($ret);
?>

源码下载地址:点击查看



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值