如何从我的php脚本发回的JSON中获取数组数据?
PHP代码:
<?php
//connects to database
include 'connect.php';
$callback = $_GET['callback'];
$query = mysql_query("SELECT * FROM users");
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
$out_string = json_encode($rows);
print $callback.'('.$out_string.');';
?>
上面的php代码将所有用户表的行放入一个数组中并对其进行JSON编码。然后将其发送回此脚本:
$.getJSON(domain_path + 'generate.php?table=' + tbname + '&callback=?', function(data) {
});
如何显示发回的JSON数组中的每一行?
例如,将发回的数据是:
([{"name":"user1","link":"google.com","approve":"true"},{"name":"user2","link":"yahoo.com","approve":"true"},{"name":"user3","link":"wikipedia.com","approve":"true"}]);
我如何使用javascript(jQuery)将其显示出来:
Name: User1 , Link: google.com , Approve:True Name: User2 , Link: yahoo.com , Approve:True Name: User3 , Link: wikipedia.com , Approve:True
答案 0 :(得分:1)
当你完成print $callback.'('.$out_string.');';
时,你已经破坏了JSON格式的字符串。发送回数组,然后循环遍历您的行并显示数据。
$out_string = json_encode(array('callback' => $callback, 'rows' => $rows));
答案 1 :(得分:0)
你应该做
function(data) {
$.each(data, function(){
$('#result').append('<p>Name:'+this.name+' Link:'+this.link+' Approve'+this.approve+'</p>');
});
}
答案 2 :(得分:0)
$.getJSON(domain_path + 'generate.php?table=' + tbname + '&callback=?', function(data) {
$.each(data, function(i, item) {
$("#mycontainer").append("<p>Name: " + item.name + "</p>");
$("#mycontainer").append("<p>Link: " + item.link + "</p>");
});
});