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 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 ?>
作者: Zjmainstay
出处: http://www.cnblogs.com/Zjmainstay/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
版权信息
分类: PHP 札记
标签: jQuery , Ajax , jsonp
作者: Leo_wl
出处: http://www.cnblogs.com/Leo_wl/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
版权信息查看更多关于jQuery $.ajax jsonp的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did46909