$.jquery ajax 返回的数据(json)显示为“未定义”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10046010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
$.jquery ajax returned data (json) displays as 'undefined'
提问by loxyboi
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.
但是,(标题、日期和时间)变量在警告框中显示为“未定义”。我尝试了多种实现 ajax 调用的方法,每次都发生同样的事情。这是我第一次尝试它,但我无法理解。
回答by Claudio Redi
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.
在这种情况下,您可以保留代码原样。