我从php中的mysql数据库返回行,然后创建所有这些行的数组,然后json编码。然后我试图将json转换为jquery的自动完成,而不是相关的。我遇到的问题是,一旦我在json中拥有它,就没有定义行。如何访问json中返回的每个“行”中的相同json.id?这是我正在使用的示例json对象
[{"id":"95833","fname":"john","lname":"walker","email":"john.walker@john.edu","major":"UNDECID ED","year":"14","gender":"0","created":"0000-00-00 00:00:00"}, {"id":"95834","fname":"joseph","lname":"train","email":"jo.train@john.edu","major":"","year":" 12","gender":"0","created":"0000-00-00 00:00:00"}]
我是访问第一个ID,还是第二个?等等
答案 0 :(得分:1)
以下是一些示例代码,展示了如何迭代数据:
var data = [{"id":"95833","fname":"john","lname":"walker","email":"john.walker@john.edu","major":"UNDECID ED","year":"14","gender":"0","created":"0000-00-00 00:00:00"}, {"id":"95834","fname":"joseph","lname":"train","email":"jo.train@john.edu","major":"","year":" 12","gender":"0","created":"0000-00-00 00:00:00"}];
for( var i = 0; i < data.length; i ++ )
{
var item = data[i];
var thisID = item.id;
// do something clever here
}
答案 1 :(得分:0)
jQuery会将JSON解析为Javascript对象数组:
data[0].id // First id
data[1].id // Second id
答案 2 :(得分:0)
我认为,我认为您正在尝试访问“列”,而不是行。顺便提一下,与大多数语言的对象模型不匹配的SQL数据库的关系模型的这个一般问题被称为“阻抗不匹配”,并且它很糟糕。您的特定问题可以通过以下方式解决(在jQuery中):
$.map(data, function(n) { return n.id } );
将返回包含所有id
值的数组。
答案 3 :(得分:0)
如果您使用的是 jQuery 1.6 ,那么它非常简单
// to get ['id', 'fname', 'lname', 'email', 'major', 'year', 'gender', 'created']
// you only need to map the first element of the data array and return the key.
var columnArray = $.map(data[0], function (val, k) {
return k;
});
快乐编码:)