JSON到JQuery:我在做什么错? [英] JSON to JQuery: What am I doing wrong?
问题描述
我对javascript和jquery开发还很陌生.我有一个要用PHP提取并格式化为JSON字符串的值表,因为JSON看起来是一种将数据导入javascript的好方法.但是我在解决javascript变量时遇到问题.
I'm fairly new to javascript and jquery development. I have a table of values I'm fetching in PHP and formatting as a JSON string, because JSON looks like a great way to get data into javascript. But I'm having trouble addressing the javascript variable.
JSON数据采用非常简单的格式.看起来像这样:
The JSON data is in a very simple format. It looks like this:
[
{"id":"1","name":"Bob","haircolor":"brown"},
{"id":"2","name":"Carol","haircolor":"Red"}
]
以此类推.没有一个条目是复杂的.只是平坦的数据行.
And so on. None of the entries are complex. It's just flat rows of data.
我正在使用JQuery中的$ .getJSON()将数据放置在像这样的变量中:
I'm using $.getJSON() from JQuery to place the data in a variable like so:
var people;
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
people.push(data);
});
根据console.log(data),对象'data'正在使用我的JSON字符串的内容填充.但是,推送会在JavaScript控制台中生成以下错误:
According to console.log(data), the object 'data' is getting populated with the contents of my JSON string. But the push is generating these errors in the javascript console:
Uncaught TypeError: Cannot read property 'length' of undefined
Uncaught TypeError: Cannot call method 'push' of undefined
我想念什么?您还需要其他信息来帮助我吗?由于这个问题,我已暂停该项目,而我只是一个JavaScript新手,无法解决它.
What am I missing? And is there any other information you need to help me on this? I've ground to a halt on this project because of this problem, and I'm just too much of a javascript newbie to figure it out.
推荐答案
变量people必须是一个数组.将第一行更改为
The variable people must be an array. Change the first line to
var people = [];
目前,"people"尚未定义,.push()方法仅适用于数组.
At the moment "people" is just undefined and the .push() method only works on arrays.
这篇关于JSON到JQuery:我在做什么错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!