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

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

  下面举一个例子来说明:

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

<?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);";
?>

则www.a.com下的客户端代码可以是:

<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;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;300px;height:200px;"></div>
<input type="button" value="test" onclick="test()" />

  在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);
        });

原文地址:https://www.cnblogs.com/georgelu/p/6494473.html