網上看到一篇博文提到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 // 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 ?>