我正在尝试获取学生详细信息的名称。 我试过这个代码,但它没有用。 请帮帮我。
我想获得学生姓名和部门。
var response = '[
{
"student": {
"id": "12",
"departmant" : "computer",
"created_date": "2015-04-16 12:05:27",
"modified_date": "2015-04-16 12:05:27"
},
"student_details": [
{
"id": "2",
"student_id": "12",
"lname": "jain",
"name": "hemant",
"created_date": "2015-04-16 12:05:27",
"modified_data": "2015-04-16 12:05:27"
}
]
}
]';
var codes = jQuery.parseJSON(response);
console.log(codes);
$.each(codes, function (key, value) {
alert(value.name);
});
答案 0 :(得分:0)
JSON应该有效,但您尝试访问的级别太高了。 JSON的结构是
Array(Object(key:value))
您正在尝试访问
Object(key:value)
为了达到你想要的目的,你需要做以下事情:
var codes = jQuery.parseJSON(response);
console.log(codes);
$.each(codes, function (key, value) {
//key will be 0, since there's only one record in the array
$.each(value, function (key2, value2) {
alert(value2.name); // which won't be defined for the first entry (student)
}
});
或
var codes = jQuery.parseJSON(response);
console.log(codes);
$.each(codes[0], function (key, value) {
alert(value.name); // which still won't be defined for the first entry (student)
});
或者,更有意义的方式:
var codes = jQuery.parseJSON(response);
console.log(codes);
$.each(codes, function (key, value) {
alert(value.student.id);
alert(value.student_details.name);
});