经过jsonp解决ajax的跨域请求问题

AJAX对于咱们来讲可能已经不是陌生的事情了,但若是你的是跨域请求,那么AJAX已经无能为力,其实这个也是能够弥补的,就是利用 jsonp。其实也不是什么技术,只是利用JS标签里面的跨域特性进行跨域数据访问,服务器返回的JS代码在客户端浏览器再次执行获得咱们想要的效果,利 用jsonp能够作到防AJAX实现跨域请求,可是咱们并不须要建立XMLHttpRequest,固然也得不到readyState,由于这并非 AJAX了。php

  下面举一个例子来讲明:html

假设须要在域名www.a.com下请求www.b.com/ajax.php,相比AJAX服务器端的代码没有什么太大的改变,关键是客户端代码,例如在ajax.php中随便写点代码:jquery

<?php
$arr =array(
    'x' => array('id'=>10,'user'=>'zhangsan'),
    '3'=>array('id'=>11,'user'=>'lisi'),
    '8' =>array('id'=>14,'user'=>'wangwu')
);
$jsondata = json_encode($arr);
echo $_GET['callback'] . "($jsondata);";
?>ajax

则www.a.com下的客户端代码能够是:json

<html>
<head>
<script>
function ck(data){
        var str = '';
        for(i in data){
            str += data[i].id + '___' + data[i].user + '<br/>';
        }
        document.getElementById('content').innerHTML=str;
}
function test(){
        var s = document.createElement('script');
        s.src = "http://www.b.com/ajax.php?callback=ck";
        head=document.getElementsByTagName('head').item(0);
        head.appendChild(s);
}
</script>
</head>
<body>
<div id="content" style="border:1px solid red;width:300px;height:200px;"></div>
 <input type="button" value="test" onclick="test()" />
</body>
</html>跨域

其 中test()函数的做用是建立script标签,动态请求www.b.com/ajax.php并传入回调函数名ck,服务器会返回js代码,就像咱们 看到的输出执行函数的代码,而且将json数据做为参数传入回调函数,和AJAX中使用的回调函数同样,实现咱们想要的效果。浏览器

  若是使用jquery则代码简洁而且更像AJAX的用法,代码示例:服务器

<script src="jquery.js"></script>
<script>
function test(){
 $.ajax({
        url:'http://www.b.com/ajax.php',
        type:'GET',
        data:{name:'xxx'},
        dataType:'jsonp',
        jsonp:'callback',
        success:function(data){
           var str = '';
           for(i in data){
            str += data[i].id + '___' + data[i].user + '<br/>';
            }
            $('#content').html(str);
        }
    });
}
</script>
<div id="content" style="border:1px solid red;width:300px;height:200px;"></div>
<input type="button" value="test" onclick="test()" />app

  在jquery中还有一个方法是,使用起来更简洁一点,只须要将函数内的代码更改成:函数

$.getJSON("http://www.b.com/ajax.php?callback=?",             function(data){                 var str = '';                 for(i in data){                     str += data[i].id + '___' + data[i].user + '<br/>';                 }                 $('#content').html(str);         });

相关文章
相关标签/搜索