如何使用jQuery显示JSON数组中的数据

时间:2012-04-04 09:13:36

标签: php jquery html json

如何从我的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

3 个答案:

答案 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>');
    });
}

在这里摆弄http://jsfiddle.net/hUkWK/

答案 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>");
  });
});