jQuery阅读JSON数据

时间:2014-03-28 05:33:03

标签: javascript php jquery json

所以我有一个数据库使用PHP通过JSON将一大堆数据传递回jQuery ..我试图从返回的数据中访问各个列,但没有运气..

我的PHP:

header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);

while($row = mysql_fetch_assoc($result)){ 
  $myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';

这是我的JS:

function getAll(){
    jQuery.ajax({
        url:'example.com/js/getAll.php',
        async: true,
        dataType: 'jsonp',
        success:function(data){
            $('.quoteList').append(data[0]);
        }
    });
}

目前,将以下内容附加到元素:

[{"id":"1","text":"The most wasted of all days is one without laughter.","author":"E.E. Cummings","status":"1"}]

所以例如..如果我想让jQuery通过data [0]到数据[92](最后一个)并将每个的作者附加到.quoteList,我怎么能这样做?我试过数据[0] [1]和数据[0] [作者]

5 个答案:

答案 0 :(得分:5)

您可以使用 $.each() 循环浏览data并附加author

$.each(data, function(i) {
    $('.quoteList').append(data[i]['author']);
});

答案 1 :(得分:2)

PHP可能有缺陷,因为json_encode被调用两次,这是不寻常的。如上所述,这将把行扁平化为JSON字符串,但仅仅是字符串,然后将JSON再次编码为字符串数组。这可能不是你想要的,因为它可以打印接收的数据,但不能访问将被解码为字符串而不是对象的行的组件。

比较https://stackoverflow.com/a/6809069/103081 - 这里PHP回显了一个带有括号()内的单个JSON对象的回调。

我怀疑修复程序看起来像https://stackoverflow.com/a/15511447/103081 并可以按如下方式进行调整:

header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);

while($row = mysql_fetch_assoc($result)){ 
  $myjsons[] = $row;
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';

一旦你有了这个,你应该为你的对象数组找回适当的JSON,并且能够在客户端使用@Felix的代码。

答案 2 :(得分:0)

你需要在数据上使用循环,试试这个

success:function(data){
    for (var i in data) {
        $('.quoteList').append(data[i]);
    }
}

答案 3 :(得分:0)

这应该有效: (更新。所有代码:)

function getAll(){
    jQuery.ajax({
        url:'example.com/js/getAll.php',
        async: true,
        dataType: 'jsonp',
        contentType: "application/json",
        success:function(data){
            var str = "";

            $(data).each(function(index, item){
                str += item.author + "  ";
            });

            $('.quoteList').append(str);
        }
    });
}

答案 4 :(得分:0)

你的问题在这里:

while($row = mysql_fetch_assoc($result)){ 
  $myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';

你需要这样的东西:

while($row = mysql_fetch_assoc($result)){ 
  $myjsons[] = $row;
}
$myjsons['callback'] = $_GET['callback'];
echo json_encode($myjsons);