美元。jquery ajax返回的数据(json)显示为“未定义”

时间:2022-10-24 21:29:12

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

这里我有一个简单的php脚本,它以json格式显示数据库中的一些值。

$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:

当点击一个图像时,这个jquery被调用:

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.

但是,(标题、日期和时间)变量在警告框中显示为“undefined”。我尝试了多种实现ajax调用的方法,每次都会发生同样的事情。这是我第一次尝试,但是我想不出来。

1 个解决方案

#1


21  

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

json字符串具有数组格式。您需要像这样访问json对象属性

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.

如果您控制的是json格式,并且不需要数组,那么使用这种格式的json对象。

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

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

在这种情况下,您可以保留您的代码。

#1


21  

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

json字符串具有数组格式。您需要像这样访问json对象属性

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.

如果您控制的是json格式,并且不需要数组,那么使用这种格式的json对象。

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

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

在这种情况下,您可以保留您的代码。