PHP ajax跨域解决

目录

 

准备阶段

nginx虚拟主机配置文件

代码准备

解决ajax跨域的问题

方法一 xhr2:

方法二 jsonp:


准备阶段

准备的域名

www.kuayu.com

domain.kuayu.com

hosts文件修改

 

nginx虚拟主机配置文件

server {
        listen       80;
        server_name  www.kuayu.com             domain.kuayu.com;
        location / {
            root   D:/wwwroot/www.kuayu.com;
            index  index.html index.htm default.html default.htm index.php default.php app.php u.php;
            include        D:/wwwroot/www.kuayu.com/up-*.conf;
        }
        autoindex off;
        include advanced_settings.conf;
        #include expires.conf;
        location ~* .*\/(attachment|attachments|uploadfiles|avatar)\/.*\.(php|php5|phps|asp|aspx|jsp)$ {
        deny all;
        }
        location ~ ^.+\.php {
            root           D:/wwwroot/www.kuayu.com;
            fastcgi_pass   bakend;
            fastcgi_index  index.php;
            fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
            fastcgi_param  PATH_INFO $fastcgi_path_info;
            fastcgi_param  PATH_TRANSLATED $document_root$fastcgi_path_info;
            include        fastcgi.conf;
        }
}

 

代码准备

两个文件index.php和server.php;index.php文件模拟客户端,主要是html代码;server.php模拟服务端响应客户端的请求。

index.php文件

<html>
<head>
    <title>跨域www.kuayu.com</title>
    <script src="js/jquery-1.11.3.js"></script>
</head>
<body>
<button type="button" class="access">请求服务器</button><button type="button" class="btn_clear">清除</button>
<div id="div"></div>
</body>
<script type="text/javascript">
    $(document).on('click','.access',function(){
        var url = 'http://www.kuayu.com/server.php';
        //var url = 'http://domain.kuayu.com/server.php';
        $.ajax(
            {
                url: url,
                type:"POST",
                dataType: "json",
                data:{name:"zhangsan",age:18},
                success: function (data) {
                    if(data.status == 'y'){
                        $('#div').text(data.info);
                    }else{
                        $('#div').text('失败');
                    }
                }
            }
        );

    });
    $(document).on('click','.btn_clear',function(){
        $('#div').text("");
    });
</script>
</html>

 

server.php文件

<?php
//echo '模拟服务器端接收请求';
$result = ['status'=>'y', 'info'=>'祝你健康幸福!'];
echo json_encode($result, JSON_UNESCAPED_UNICODE);

 

访问页面http://www.kuayu.com/index.php,打开浏览器控制台,点击页面的【请求服务器】按钮,ajax请求的url是http://domain.kuayu.com/server.php,控制台出现如下

 

 

红色字体为:

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

 

 

 

解决ajax跨域的问题

方法一 xhr2:

参考:http://www.jb51.net/article/77470.htm

http://www.cnblogs.com/xiaoxiao2014/p/4819619.html

server.php文件开头添加如下代码:

//header("Access-Control-Allow-Origin:*");
//header("Access-Control-Allow-Methods:GET,POST");

$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : ''; 
 
$allow_origin = array( 
    'http://client1.runoob.com', 
    'http://client2.runoob.com' 
); 
 
if(in_array($origin, $allow_origin)){ 
    header('Access-Control-Allow-Origin:'.$origin);       
}

 

 

 

方法二 jsonp:

说说json和jsonp,也许你会豁然开朗,参考:http://kb.cnblogs.com/page/139725/

index.php文件,注意dataType:"jsonp", jsonpCallback:"cb",jsonCallback的值可以随意指定,在目标服务器端需要用到这个jsonpCallback的值;虽然设置type:"POST",但是以get方式请求

<html>
<head>
    <title>跨域www.kuayu.com</title>
    <script src="js/jquery-1.11.3.js"></script>
</head>
<body>
<button type="button" class="access">请求服务器</button><button type="button" class="btn_clear">清除</button>
<div id="div"></div>
</body>
<script type="text/javascript">
    $(document).on('click','.access',function(){
        var url = 'http://domain.kuayu.com/server.php';
        $.ajax(
            {
                url: url,
                type:"POST",
                dataType: "jsonp",
                data:{name:"zhangsan",age:18},
                jsonpCallback:"cb",
                success: function (data) {
                    if(data.status == 'y'){
                        $('#div').text(data.info);
                    }else{
                        $('#div').text('失败');
                    }
                },
//                error:function(XMLHttpRequest, textStatus, errorThrown) {
//                    alert(XMLHttpRequest.status);
//                    alert(XMLHttpRequest.readyState);
//                    alert(textStatus);
//                }
            }
        );
    });
    $(document).on('click','.btn_clear',function(){
        $('#div').text("");
    });
</script>
</html>

 

server.php文件,返回的信息格式是json,在json格式字符串外面需要处理成 cb( json信息) 的字符串,这里的cb就是客户端的jsonpCallback的值。

$result = ['status'=>'y', 'info'=>'祝你健康幸福!'];
$str = json_encode($result, JSON_UNESCAPED_UNICODE);


if(isset($_GET['callback']){
    $str = $_GET['callback'] .'('. $str . ')';
}

echo $str;

 

请求如下图,实际上是以GET方式请求:

 

响应如下图:

 

 

其他解决办法后继补充

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值