It's our wits that make us men.

跨域获取数据jsonp

Posted on By wen jay

Build Status Coverage Status

简单实现jsonp

跨域服务器 : ./testjsonp.js

callback("come from server data ");

本地服务器: ./localhtml.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
    <script type="text/javascript"> 
        function callback(data){
            alert('我是本地函数,可以被跨域的remote.js文件调用,远程js带来的数据是:' + data); 
        }; 
    </script> 
    <script type="text/javascript" src="http://liushi.tech/php/phpbase/jsonp/testjsonp.js"></script>

</body>
</html>

运行localhtml.html

php拼接字符串实现jsonp

跨域服务器 : ./testserver.php

<?php

    $age=array("Bill"=>"60","Steve"=>"56","Mark"=>"31");

    $callback = $_GET['callback'];

    echo $callback . "(" . json_encode($age) . ")";

?>

本地服务器: ./localhtml.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        function callbackFunction(data){
            console.log(data);
        }; 
    </script>

    <script type="text/javascript" src="http://liushi.tech/php/phpbase/jsonp/testserver.php?callback=callbackFunction"></script>

</body>
</html>

运行localhtml.html

jQuery实现jsonp

跨域服务器 : ./testserver.php

<?php

    $age=array("Bill"=>"60","Steve"=>"56","Mark"=>"31");

    $callback = $_GET['callback'];

    echo $callback . "(" . json_encode($age) . ")";

?>

本地服务器: ./localhtml.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
      <script type="text/javascript" src=jquery.min.js"></script>
      <script type="text/javascript">
     jQuery(document).ready(function(){
        $.ajax({
             type: "get",
             async: false,
             url: "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998",
             dataType: "jsonp",
             
              //传递给请求处理程序或页面的,
             //用以获得jsonp回调函数名的参数名(一般默认为:callback)
             jsonp: "callback",
             
             //自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,
             //也可以写"?",jQuery会自动为你处理数据
             jsonpCallback:"flightHandler",
             success: function(data){
             console.log('请求成功',data)
             },
             error:function(err){
             console.log('请求失败',err)

}

         });
     });
     </script>
     </head>
  <body>
  </body>
 </html>