一个关于 jquery 和 php 的 jsonp 例子(与后台PHP成功通信)

<script>
       $(document).ready(function(){
          $.ajax({
               url:'http://localhost/test/jsonp.php',
               dataType:"jsonp", //重点,使用jsonp方式解决跨域问题
               jsonp:"jsonpcallback", //回调函数名,和php端统一
               timeout: 5000,
               success:function(data, status){
                   alert('success: ' + status);
                   var $ul = $("<ul></ul>");
                   $.each(data,function(i,v){
                       $("<li/>").text(v["id"] + " " + v["name"]).appendTo($ul)
                   });
                   $("#res").append($ul);
               },
               error:function(XHR, textStatus, errorThrown){
                   alert('error: ' + textStatus);
                   alert('error: ' + errorThrown);
               }
          });
       });
</script>
$jsonp = $_GET['jsonpcallback'];
$arr = array(
  'id' => '1',
    'name' => 'test'
);
echo $jsonp, '([', json_encode($arr), '])'; //返回的数据中括号数组好像是必须的
?>

 

posted @ 2014-05-04 17:07  小小有  阅读(311)  评论(0编辑  收藏  举报