这里我有一个简单的 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;
这显示得很好,这是一个输出示例:
[{"title":"Torus","date":"2012-04-04","time":"23:06:14"}]
然后,当单击图像时,将调用此 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);
}
});
但是,(标题、日期和时间)变量在警报框中显示为“未定义”。 我尝试了多种实现 ajax 调用的方法,但每次都会发生同样的事情。 这是我第一次尝试,但我不明白。
最佳答案
您的 json 字符串具有数组格式。您需要像这样访问 json 对象属性
title = data[0].title;
alert(title);
date = data[0].date;
alert(date);
time = data[0].time;
alert(time);
如果您控制 json 格式并且不需要数组,请使用此格式的 json 对象。
{"title":"Torus","date":"2012-04-04","time":"23:06:14"}
在这种情况下,您可以保持代码不变。
关于jquery - $.jquery ajax返回的数据(json)显示为 'undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10046010/