AJAX的跨域问题

来源:互联网 发布:双11是天猫还是淘宝 编辑:程序博客网 时间:2024/05/17 22:23

首先说明出现跨域问题的情况:
由于在工作中需要使用AJAX请求其他域名下的请求,但是会出现拒绝访问的情况,这是因为基于安全的考虑,AJAX只能访问本地的资源,而不能跨域访问。
比如说你的网站域名是aaa.com,想要通过AJAX请求bbb.com域名中的内容,浏览器就会认为是不安全的,所以拒绝访问。会出现跨域问题的几种情况:
这里写图片描述
1.如果跨域的时候再用原始的ajax(创建xhr对象,感知ajax状态,创建请求,发送请求),就会出现如下错误:

 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8020' is therefore not allowed access. The response had HTTP status code 404.

当然,有的时候也不会出现这样的错误,这是因为服务端php头部有如下设置(这时候iE低版本可能有问题):

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

2.这时候可以用JSONP方法,简单用一个百度关键词API示例:

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title></title>        <style type="text/css">            .wrap{                width: 500px;                border:1px solid #ccc;                margin: 100px auto;            }            .search{                font:20px/50px "微软雅黑";                color:#000;            }            .keywords{                width: 400px;                height: 50px;                border:1px solid #008000;                border-radius: 5px;                font:20px/50px "微软雅黑";                color:#000;                padding-left:10px ;            }            .btn{                width: 80px;                height: 50px;                border:1px solid #008000;                border-radius: 5px;                font:20px/50px "微软雅黑";                color:#000;            }            ul{                /*display: none;*/            }        </style>    </head>    <body>        <div class="wrap">            <div class="search">                <input type="text" class="keywords" value="" />                <button class='btn'>搜索</button>            </div>            <div class="msg">                <ul class="list">                </ul>            </div>        </div>        <script type="text/javascript">            function $(c){                return document.getElementsByClassName(c)[0];            }            function fn1(data){                var str='';                if(data.s.length){                    $('list').style.display='block';                    for(var i=0;i<data.s.length;i++){                        str+='<li><a href="https://www.baidu.com/s?wd='+data.s[i]+'" target="_blank">'+data.s[i]+'</a></li>';                    }                    $('list').innerHTML=str;                }else{                    $('list').style.display='none';                }            }            $('keywords').onkeyup=function(){                if(this.value !=''){                    var oScript=document.createElement('script');                    var $url='http://suggestion.baidu.com/su?wd='+$('keywords').value+'&cb=fn1';//注意这里的cb是一个回调函数,有时候是callback,这是远程服务端定义的。下面示例                    oScript.src=$url;                    document.body.appendChild(oScript);                }else{                    $('list').style.display='none';                }            }        </script>    </body></html>

2.1再来一个简单示例(跨域请求数据),html代码如下:

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title></title>    </head>    <body>        <script type="text/javascript">            function fn1(data){                alert(data.username);            }            var script=document.createElement('script');            script.src='http://www.cqzhangs.top/01.php?&callback=fn1';//我这里的地址是之前测试的,callback为回调函数            document.getElementsByTagName('head')·[0].appendChild(script);        </script>    </body></html>

运行结果如图:
这里写图片描述
然后远程的php代码如下:

<?php    header("Content-type: text/html; charset=utf-8");     $callback=$_GET['callback'];    $userInfo=array('id'=>1,'username'=>'king');    $res=json_encode($userInfo);    echo  $callback."({$res})";?>

2.2另外jquery实现:

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title></title>    </head>    <body>        <button id="btn">ajax请求</button>        <button id="btn2">jsonp请求</button>        <button id="btn3">getJSONP</button>        <script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>        <script type="text/javascript">//          $('#btn').click(function(){//              $.ajax({//                  url:"http://www.cqzhangs.top/01.php",//                  type:'GET',//                  dataType:'json',//                  success:function(data){//                      alert(data.username);//                  },//                  error:function(){//                      alert('error')//                  },//              });//          });  这是jQuer的ajax请求,会报上述中的错//          Jsonp(只能get)            $('#btn2').click(function(){                $.ajax({                    url:"http://www.cqzhangs.top/01.php",                    type:'GET',                    dataType:'jsonp',                    jsonp:'callback',//可不写                    jsonpCallback:'fn',//可不写                    success:function(data){                        alert(data.username);                    },                });            });//          可简写如下            $('#btn3').click(function(){                $.getJSON('http://www.cqzhangs.top/01.php?callback=?',function(data){                    alert(data.username);                })            });        </script>    </body></html>
原创粉丝点击