$ .jquery AJAX返回的数据(JSON)显示为“未定义” [英] $.jquery ajax returned data (json) displays as 'undefined'

查看:1140
本文介绍了$ .jquery AJAX返回的数据(JSON)显示为“未定义”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我有一个JSON格式显示从一个数据库中的一些值的简单的PHP脚本。

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"}]

然后将图像点击这个jQuery的时候被调用:

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

不过,(标题,日期和放大器;时间)变量显示的警告框为未定义。 我试着执行Ajax调用,同样的事情发生的每一次的多种方式。 这是我第一次尝试了好吗,但我想不出它。

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.

推荐答案

您JSON字符串具有阵列形式。您需要访问这样的JSON对象属性

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

如果你控制了JSON格式,数组是没有必要的,使用JSON对象与此格式。

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"}

在这种情况下,你可以保持您的code因为它是现在。

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

这篇关于$ .jquery AJAX返回的数据(JSON)显示为“未定义”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆