How to add json callback to php file?
Created a javascript widget. Had problems with same origin policy. I added the callback to the php file like this:
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);
Now I don't know how to add the callback to the data.php file. This is what I've tried:
while($info = mysql_fetch_array($result)){
$json = array();
$json['coupon_name'] = $info['label'] ;
$json['retailer_name'] = $info['name'] ;
$json['logo_image'] = $info开发者_StackOverflow社区['logo_image'];
$json['permalink'] = $info['permalink'];
$data[] = $json;
}
$data2 = json_encode($data);
echo $data2;
echo $_GET['json_callback'] . '(' . $data2 . ');';
Remove echo $data2; - currently your page generates invalid javascript
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);
精彩评论