Trying to parse JSON file with jQuery
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"
}
]
}
}
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>');
});
});
}
Is there something I am doing wrong?
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 ;))
s.nametry: <br/>
$("document").ready(function() {
$.getJSON(fileUrl,
function(data)
{
$("#div-my-table").text("<table>");
$.each(data, function(i, item) {
$("#div-my-table").append("<tr><td>" + item.prop1 +"</td><td>" + item.prop2 + "</td></tr>");
});
$("#div-my-table").append("</table>");
});
});
精彩评论