ajax跨域问题

两个不同域名的程序在处理ajax的时候肯定会有跨域的存在,一种方式是通过jsonp,一种是通过请求本域名,然后后端PHP转发curl,还有一种比较简单 通过header头来实现,例如

现在有两个域名 www.host1.com 和 www.host2.com 在host1.com下面请求host2.com下面的Php文件。

例如 http://www.host1.com/index.html中这样写

<!DOCTYPE HTML>
<html lang="en-US"><head>
    <meta charset="UTF-8">
    <title></title>
    <script src="http://cdn.bootcss.com/jquery/2.2.4/jquery.js"></script>
</head>
<body>
    <script type="text/javascript">
        $(function(){
            $.post("http://www.host2.com/test.php",{"name":"lizhaoyao","sex":"man"},function(res){
                console.log(res);
            },"json");
        });
    </script>
</body>
</html>

一个很简单的ajax请求,传送 name 和sex 给 http://www.host2.com/test.php 该文件这样写

<?php

$ret = array(  
    'name' => isset($_POST['name'])? $_POST['name'] : '',  
    'sex' => isset($_POST['sex'])? $_POST['sex'] : ''  
);  
echo json_encode($ret); 
?> 

然后通常情况下会出现一个跨域提醒 

XMLHttpRequest cannot load http://www.host2.com/test.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 404.

然后我们可以加一段代码

$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
header('content-type:application:json;charset=utf8');
header('Access-Control-Allow-Origin:'.$origin);
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');

如图:

<?php

$ret = array(  
    'name' => isset($_POST['name'])? $_POST['name'] : '',  
    'sex' => isset($_POST['sex'])? $_POST['sex'] : ''  
);  
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';  
header('content-type:application:json;charset=utf8');  
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);  
exit();

再看效果

xhr请求成功!

 

posted @ 2016-09-20 15:18  李照耀  阅读(480)  评论(5编辑  收藏  举报