2e2e2 发表于 2014-4-18 10:18:14

php中jsonp的跨域实例

我们现在www.test.com这个域名下面有这么个html文件testjsonp.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
   <title>Untitled Page</title>
      <script type="text/javascript" src="jquery-1.7.2.min.js"></script>
      <script type="text/javascript">
   jQuery(document).ready(function(){   
      $.ajax({
             type: "GET",
             async: false,
             //url: "http://test/jsonp.php",
             url:"http://mytaobao.com/jsonp.php",
             dataType: "jsonp",
             jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
             jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
             success: function(json){
               alert('您查询到航班信息:票价: ' + json.price + ' 元,余票: ' + json.tickets + ' 张。回调函数名为: '+json.func);
             },
             error: function(){
               alert("fail");
             }
         });
   });
   </script>
   </head>
<body>
</body>
</html>
注意,要真正运行上面的代码可能需要jquery的文件,你可以将<script type="text/javascript" src="jquery-1.7.2.min.js"></script>改为你目录中jquery的文件路径:

如:<script type="text/javascript" src="js/jquery.js"></script>
然后,你可以再找个另外一个域名的web目录,将文件jsonp.php:

<?php

$callback = $_GET["callback"];
$a = array(
    'code'=>'CA1998',
    'price'=>'6000',
    'tickets'=>20,
    'func'=>$callback,
);
$result = json_encode($a);
echo "flightHandler($result)";
exit;

放到这个目录下面去。这样就可以测试了。 直接在浏览器访问testjsonp.html.就可以看到效果了。

页: [1]
查看完整版本: php中jsonp的跨域实例