如何将json回调添加到php文件?
创建了一个 JavaScript 小部件。同源政策存在问题。我将回调添加到 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 . ');';
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['logo_image'];
$json['permalink'] = $info['permalink'];
$data[] = $json;
}
$data2 = json_encode($data);
echo $data2;
echo $_GET['json_callback'] . '(' . $data2 . ');';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
删除 echo $data2; - 当前您的页面生成无效的 javascript
Remove echo $data2; - currently your page generates invalid javascript
JavaScript:
PHP:
Javascript:
PHP: