jsonp实现跨域请求

jsonp实现跨域请求

ps:本人亲测,阿里云2核4G5M的服务器性价比很高,新用户一块多一天,老用户三块多一天,最高可以买三年,感兴趣的可以戳一下:阿里云折扣服务器

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="http://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 
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',                   //回调函数名
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 ?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值