我要疯了,试图从此json中解析每个“分区”的“名称”和“ id”属性,并将其转换为一个选择:
[{"division":{"name":"Solo Male","coed":false,"size":1,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":1}},{"division":{"name":"Solo Female","coed":false,"size":1,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":2}},{"division":{"name":"4 Person Male","coed":false,"size":4,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":9}},{"division":{"name":"4 Person Female","coed":false,"size":4,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":10}},{"division":{"name":"4 Person Coed","coed":true,"size":4,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-10-29T10:46:28-04:00","id":11}},{"division":{"name":"3 Person Male","coed":false,"size":3,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":6}},{"division":{"name":"3 Person Female","coed":false,"size":3,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":7}},{"division":{"name":"3 Person Coed","coed":true,"size":3,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-10-29T10:46:22-04:00","id":8}},{"division":{"name":"2 Person Male","coed":false,"size":2,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":3}},{"division":{"name":"2 Person Female","coed":false,"size":2,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":4}},{"division":{"name":"2 Person Coed","coed":true,"size":2,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-10-29T10:46:16-04:00","id":5}}]
这是我无法上班的代码:
jQuery.each(data, function(i,division) {
$('#squad_division').append( $('<option value="'+ division.id+'">'+ division.name +'</option>'));
我知道我只是在尝试访问“ division.id”和“ division.name”的地方缺少一些简单的东西,但这使我难以理解。
在此先感谢您的帮助。
干杯
最佳答案
由于JSON的结构,您需要将division.id
更改为division.division.id
。这是您几乎完全相同的代码正常运行的jsfiddle:http://jsfiddle.net/RqwBT/1/
基本上,您的division
变量是数组中的单个键(data
变量),它是一个对象,并且该对象具有一个属性:division
(具有您要访问的子属性)。
jQuery.each(data, function(i,division) {
$('#squad_division').append( '<option value="'+ division.division.id+'">'+ division.division.name +'</option>');
});
注意,我在您的append语句中删除了HTML周围的
$()
,因为这会产生不必要的开销。我通过在每个函数内调用
console.log(division);
来弄清楚这一点,该函数允许我一次检查单个数组键,以查看如何访问该对象的信息。当我从新来源加载JSON时,这是我的标准做法。关于jquery - 如何访问这些属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8188382/