尝试使用jQuery解析JSON文件 [英] Trying to parse JSON file with jQuery
问题描述
我正在尝试使用下面的确切结构来解析JSON文件.
I am trying to parse a JSON file with the exact stucture as in the following.
{
"students": {
"student": [
{
"id": 1,
"name": "John Doe",
"image": "pic1.jpg",
"homepage": "http: //www.google.com"
},
{
"id": 2,
"name": "Jane Doe",
"image": "pic1.jpg",
"homepage": "http: //www.google.com"
}
]
}
}
我正在使用以下jQuery函数:
I am using the following jQuery function:
function GetStudents(filename)
{
$.getJSON(filename, function(data){
$.each(data.student, function(i,s){
var id = s.id;;
var name = s.name;;
var img = s.image;;
var homepage = s.homepage;
$('.networkTable').append('<tr><td><img src="' + img + '" class="picEven pic" width="33" height="35"></td><td><a href="'+ homepage + '" class="networkLink">' + name + '</a></td></tr>');
});
});
}
我在做错什么吗?
推荐答案
您没有访问正确的元素. data
不指向students
,它指向最外面的元素{students:...}
(students
是它的一个属性).数组包含在data.students.student
:
You are not accessing the correct element. data
does not point to students
, it points to the outer most element {students:...}
(students
is an property of it). The array is contained in data.students.student
:
$.each(data.students.student, function() {
//...
});
更多说明:
Further notes:
-
如果只访问一次属性,则无需创建局部变量(但当然,它可能更易读).
You don't need to create a local variable if you access a property only once (but of course it might be more readable).
具有连续的分号;;
并没有错,但这是不必要且令人困惑的(至少使我感到困惑;))
While having consecutive semicolons ;;
is not wrong, it is unnecessary and confusing (at least it confuses me ;))
这篇关于尝试使用jQuery解析JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!