在Javascript变量中访问JSON数据 [英] Accessing JSON data in a Javascript variable

查看:63
本文介绍了在Javascript变量中访问JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不得不提出这个问题令人尴尬,但我承认我是一个没有经验的Javascript开发人员,而我无法理解这一点。希望这对其他人来说简单易行,我想提前感谢所有人在这个网站不断提供的帮助。

It's embarrassing to have to ask, but I freely admit I'm an unseasoned Javascript developer, and I just can't figure this out. Hopefully, this will be dead simple for someone else, and I want to thank everyone here ahead of time for the help this site continually provides me.

几天前,我问了这个问题,我不再收到该错误。但我试图实际访问存储在变量中的数据。我的JSON看起来像这样:

A couple days ago, I asked this question, and am no longer getting that error. But I've run into a wall trying to actually access the data stored in the variable. My JSON looks like this:

[
    {"id":"1","name":"Bob","haircolor":"Brown"},
    {"id":"2","name":"Carol","haircolor":"Red"}
]

它会变成这样的变量:

var people=[];
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
    people.push(data);
});

感谢将人初始化为数组,我不再收到任何错误消息。但我也无法访问人们的内容。 people.length 返回0,人[0] 人[1] 未定义。

Thanks to initializing people as an array, I no longer get any error messages. But I can't access the contents of people, either. people.length returns a 0, and people[0] and people[1] are undefined.

它就在那里,我知道它就在那里,但我有一个时间搞清楚在哪里。

It's there, I know it's all there, but I'm having a devil of a time figuring out where.

推荐答案

试试这个: http: //jsfiddle.net/hUq7k/

$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
    $.each(data, function(i, people){
       console.log(people.id); //<------this should output "1, 2"
    });
});

确保您获得响应数据

这篇关于在Javascript变量中访问JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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