2011-09-29 39 views
0

创建了一个javascript小部件。有相同的原产地政策的问题。我添加回调到这样的PHP文件:如何将json回调添加到php文件?

var jsonp_url = "http://www.example.com/widget/data.php?json_callback=?"; 
     $.getJSON(jsonp_url, function(data) { 



      for (var i=0;i<data.length-1; i++) { 

      var li = document.createElement("li"); 
      li.setAttribute("class", "top-coupon"); 


      var coupon_details = document.createElement("div"); 
      coupon_details.setAttribute("class", "coupon-details"); 
      coupon_details.innerHTML=data[i].coupon_name; 

      li.appendChild(coupon_details); 


      var image = document.createElement("img"); 
      image.setAttribute("src", "http://static.example.com/images/logos/" + data[i].logo_image); 
      image.setAttribute("class","logo-image"); 
      image.setAttribute("width","40px"); 
      image.setAttribute("height","40px"); 


      li.appendChild(image); 




      ul.appendChild(li); 

      } 
     }); 
     widget.appendChild(ul); 

现在我不知道如何将回调添加到data.php文件。这是我试过的:

 while($info = mysql_fetch_array($result)){ 

     $json = array();  
    $json['coupon_name'] = $info['label'] ; 
    $json['retailer_name'] = $info['name'] ; 
    $json['logo_image'] = $info['logo_image']; 
    $json['permalink'] = $info['permalink']; 
    $data[] = $json; 
      } 
      $data2 = json_encode($data); 
      echo $data2; 
      echo $_GET['json_callback'] . '(' . $data2 . ');'; 
+0

你为什么不使用'功能(数据){}''你$ .getJSON的一部分'?至少它是你的回调。 – Marco

+0

当直接在我的浏览器中加载data.php时,我看到数据输出两次。然而,小部件没有显示任何东西...... – PaperChase

+0

用'echo json_encode($ data)'结束你的php脚本。不要回应更多。 – Marco

回答

1

Remove echo $ data2; - 目前你的页面生成无效的JavaScript

+0

哇!那样做了!非常感谢。 – PaperChase

0

的Javascript:

$.getJSON("http://www.example.com/widget/data.php",function(data){ 
    // data is your JSON Object 
}); 

PHP:

$data = array(); 
while($info = mysql_fetch_array($result)) $data[]=$info; 
echo json_encode($data);