Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

$.jquery ajax returned data (json) displays as 'undefined'

Here I have a simple php script which displays some values from a database in json format.

$source = $_GET['source'];

$query = mysql_query("SELECT * FROM images WHERE big_thumb = '" . $source . "'");

$results = array();

while($row = mysql_fetch_array($query))
{
   $results[] = array(
      'title' => $row['title'],
      'date' => $row['upload_date'],
      'time' => $row['upload_time']
   );
}

$json = json_encode($results);

echo $json;

This displays fine, heres an output example:

[{"title":"Torus","date":"2012-04-04","time":"23:06:14"}]

Then when an image is clicked this jquery is called:

var image_src = $(this).attr("alt"); // <= This works fine

    $.ajax({
        url: 'inc/get_image_details.php',
        data: {source : image_src},
        dataType: "json",
        success: function(data)
        {
            title = data.title;
            alert(title);

            date = data.date;
            alert(date);

            time = data.time;
            alert(time);
        }
    });

However, the (title, date & time) variables display as 'undefined' in the alert box. I've tried multiple ways of implementing the ajax call and the same thing happens every time. It is the first time I've tried it alright but I can't figure it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your json string has an array format. You need to access the json object properties like this

title = data[0].title;
alert(title);

date = data[0].date;
alert(date);

time = data[0].time;
alert(time);

If you control the json format and an array is not necessary, use a json object with this format.

{"title":"Torus","date":"2012-04-04","time":"23:06:14"}

In this case you can keep your code as it is now.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...