Tips:点此可运行HTML源码

jQuery $.ajax jsonp

网上看到一篇博文提到jsonp(包括IE6在内的大多浏览器支持的标准跨域数据访问方式),搜到一篇做了很详细介绍的博文,自己动手测试了一番。下面是测试代码:

 1 <html>
 2 <head>
 3     <title>jQuery $.ajax jsonp</title>
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5     <meta http-equiv="Content-Language" content="zh-CN" />
 6     <script type="text/javascript" src="https://files.cnblogs.com/Zjmainstay/jquery-1.6.2.min.js"></script>
 7 </head>
 8 <body>
 9 <div id="myData"></div>
10 <script type="text/javascript">
11 
12 /*
13     当前文件为:http://www.test.com/index.html
14 */
15 // function getName(){}  //如果这里声明了getName函数,则回调处理调用此函数。否则,调用success指定函数,谢谢@soj 的指正
16 $(document).ready(function(){
17     $.ajax({
18         url:'http://www.wp.com/getData.php',       //跨域到http://www.wp.com,另,http://test.com也算跨域
19         type:'GET',                                //jsonp 类型下只能使用GET,不能用POST,这里不写默认为GET
20         dataType:'jsonp',                          //指定为jsonp类型
21         data:{"name":"Zjmainstay"},                //数据参数
22         jsonp:'callback',                          //服务器端获取回调函数名的key,对应后台有$_GET['callback']='getName';callback是默认值
23         jsonpCallback:'getName',                   //回调函数名,如果声明了jsonpCallback指定的函数,则走声明的函数,如果没有声明jsonpCallback指定的函数,则走success指定的函数。
24         success:function(result){                  //成功执行处理,对应后台返回的getName(data)方法。
25             $("#myData").html('1、My name is '+result.name+'.I\'m '+result.age+' years old.<br />');
26         },
27         error:function(msg){
28             alert(msg.toSource());                 //执行错误
29         }
30     }); 
31 
32     /* 测试跨域错误 */
33     $.ajax({
34         url:'http://www.test.com/getData.php',       //正常
35         // url:'http://test.com/getData.php',        //跨域到http://test.com
36         type:'GET',                    //这里是普通ajax,可以用POST
37         dataType:'json',
38         data:{"name":"Zjmainstay"},
39         success:function(result){
40             $("#myData").append('2、My name is '+result.name+'.I\'m '+result.age+' years old.');
41         },
42         error:function(msg){
43             alert(msg.toSource());                //跨域错误会执行到这里
44         }
45     });
46 });
47 </script>
48 </body>
49 </html>

文件:http://www.wp.com/getData.php

1 <?php
2     $data = array(
3         "name"=>$_GET['name'],
4         "age"=>23,
5     );
6     echo $_GET['callback']."(".json_encode($data).")";        //等价:echo 'getName({"name":"Zjmainstay","age":23})';
7 ?>

文件:http://www.test.com/getData.php(不跨域),同样是http://test.com/getData.php(跨域)

1 <?php
2     $data = array(
3         "name"=>$_GET['name'],
4         "age"=>23,
5     );
6     echo json_encode($data);
7 ?>

 

posted @ 2013-02-01 15:20  Zjmainstay  阅读(2037)  评论(7编辑  收藏  举报