简体   繁体   中英

jQuery reading JSON Data

So I have a database pass a whole bunch of data using PHP back to jQuery through JSON.. I'm trying to access individual columns from the returned data but no luck..

My 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) . ')';

Here's my JS:

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

Currently that appends the following to the element:

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

So for example.. if I wanted the jQuery to go through data[0] to data[92] (the last one) and append the author of each to .quoteList, how could I do that? I've tried data[0][1] and data[0][author]

You can use $.each() to loop through the data and append the author :

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

The PHP might be defective because json_encode is called twice, and this is unusual. As written this would be flattening the rows into JSON strings, but mere strings nonetheless, which then get JSON encoded again into an array of strings. This is probably not what you intended, as it would be making it possible to print the received data but not access the components of rows which will be decoded to strings and not objects.

Compare https://stackoverflow.com/a/6809069/103081 -- here the PHP echoes back a callback with a single JSON object inside parenthesis () .

I suspect the fix looks like https://stackoverflow.com/a/15511447/103081 and can be adapted as follows:

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) . ')';

Once you have this, you should be getting back proper JSON for your array of objects and be able to use @Felix's code on the client side.

you need to use loop on your data, try this

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

This should work: (upd. all code:)

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);
        }
    });
}

Your problem is here:

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

you need something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM