Jsonp请求数据

demo.html

 

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6 </head>
 7 <body>
 8     <script type="text/javascript">
 9         //造轮子
10         function foo(url,callback,fn = "fasdasdasdassaasd") {
11             window[fn] = callback;
12             var dom = document.createElement("script");
13             dom.src = `${url}?fn=${fn}`;
14             document.body.appendChild(dom);
15         }
16 
17         foo("data.php",function(data) {
18             console.log(data);
19         });
20 
21 
22     </script>
23 </body>
24 </html>

 

data.php

 1 <?php
 2 //jsonp
 3 $fn = $_GET["fn"];
 4 $people = array(
 5     "people" => array(
 6         array("name" => "小明","age" => 13),
 7         array("name" => "小花","age" => 15)
 8     )
 9 );
10 
11 echo "$fn(" . json_encode($people) . ")";

 

posted @ 2018-07-13 17:28  Visionarie  阅读(110)  评论(0编辑  收藏  举报