跨域问题之jsonp的实现

jsonp是一种json数据的使用方式,可以实现不同域名之间的请求和发送数据。

客户端实现方式:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript"> var flightHandler = function(data){ alert(data); } var url = "http://119.29.176.18/jsonp.php?jsoncallback=flightHandler"; // 创建script标签,设置其属性 var script = document.createElement('script'); script.setAttribute('src',url); // 把script标签加入head,此时调用开始 document.getElementsByTagName('head')[0].appendChild(script); </script>
</head>
<body>

</body>
</html>

服务器端实现方式:

<?php header('Content-type: application/json'); //获取回调函数名 $jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']); //json数据 $json_data = '["customername1","customername2"]'; //输出jsonp格式的数据 echo $jsoncallback . "(" . $json_data . ")"; ?>

jquery实现客户端:

jQuery(document).ready(function(){
        $.ajax({
             type: "get",async: true,url: "http://119.29.176.18/jsonp.php",dataType: "jsonp",jsonp: "jsoncallback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback) 
             success: function(json){
                alert(json);
             },error: function(){
                 alert('fail');
             }
         });
     });

不正确之处还望指正。

相关文章

文章浏览阅读2.4k次。最近要优化cesium里的热力图效果,浏览...
文章浏览阅读1.2w次,点赞3次,收藏19次。在 Python中读取 j...
文章浏览阅读1.4k次。首字母缩略词 API 代表应用程序编程接口...
文章浏览阅读802次,点赞10次,收藏10次。解决一个JSON反序列...
文章浏览阅读882次。Unity Json和Xml的序列化和反序列化_uni...