今天遇到一个ajax请求跨域的问题,demo如下:
一、getJson方式
<html> <head> <script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script> </head> <body> <div id="images"> </div> <script> $.getJSON("http://192.168.95.155/1.PHP?callback=?",{format:"json"},function(data){alert(data.format);}); </script> </body> </html>
<?PHP $callback=$_GET['callback']; // $callback="callback"; $data=json_encode(array("info"=>"OK","format"=>$_GET['format'])); echo $callback."(".$data.")"; ?>
二、Ajax底层函数方式
1、客户端代用代码:
<html> <head> <Meta charset="utf-8"> <script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script> </head> <body> <div id="images">点击提交按钮改变内容</div> <input type="button" value="提交" onclick="SendData()"/> <script type="text/javascript"> function SendData() { $.ajax({ type: "GET",async: false,url: "http://192.168.95.155/2.PHP",dataType: "jsonp",jsonp: "callback",success: function(data){ //alert(data.info); $("#images").html(data.info); },error: function(){ alert('fail'); } }); } </script> </body> </html>
2、 服务器代码:
<?PHP $callback=$_GET['callback']; $data=json_encode(array("info"=>"ajax跨域请求","format"=>"json")); echo $callback."(".$data.")"; ?>
参考:http://www.aitiblog.com/PHP/284.html