PHP ajax跨域解决

来源:互联网 发布:网络剧小心超人与伽罗 编辑:程序博客网 时间:2024/06/09 19:01

准备阶段

准备的域名
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的值可以随意指定,在目标服务器端需要用到这个值"cb";虽然设置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);echo "cb($str)";

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


响应如下图:



其他解决办法后继补充
0 0
原创粉丝点击