简单JSONP跨域请求

JSONP原理:利用<script>标签的src属性实现跨域的请求。可在URL中提供回调函数的名字。后台进过处理后将数据以回调函数参数的形式返回。

demo:JSONP请求不同端口的数据

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <title>跨域小demo</title>
 5     <meta http-equiv="Conent-Type" content="text/html" charset="utf-8">
 6 </head>
 7 <body>
 8     <h1>这里是端口1!</h1>
 9     <script type="text/javascript">
10     function say(words) {
11        alert(words);
12     }
13     </script>
14     <script type="text/javascript" src="http://localhost:8083/demo.php?callback=say"></script>
15 </body>
16 </html>
1 <?php
2 $type = isset($_GET['type']) ? $_GET['type'] : '';
3 $callback = isset($_GET['callback']) ? $_GET['callback'] : '';
4 $json = '"HelloWord!"';
5 if (!empty($callback)) {
6    $json = $callback . '(' . $json . ')';
7 }
8 echo $json;
9 ?>

 效果:

posted @ 2016-03-27 17:30  前端菜鸟——一只小熊  阅读(291)  评论(0编辑  收藏  举报