我需要从嵌套数组中选择值,这是我的代码,
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js">
</script>
<script>
$(document).ready(function(){
$.getJSON('userdetails.json', function(data) {
$.each(data, function(i,obj){
$("#placeholder").append('<p>'+obj.firstName+","+obj.lastName+'</p>');
});
});
});
</script>
</head>
<body>
<div id="placeholder">
<p>line1</p>
<p>line2</p>
</div>
</body>
</html>
这是我的userdetails.json
{"users":[
{
"firstName":"user1",
"lastName":"lastname1",
"joined": {
"month":"January",
"day":12,
"year":2012
}
},
{
"firstName":"user2",
"lastName":"lastname2",
"joined": {
"month":"April",
"day":28,
"year":2010
}
}
]}
输出:
line1
line2
undefined,undefined
这是我得到的输出,但我需要显示名字和姓氏。
答案 0 :(得分:1)
您需要将data.users
而不是data
传递给每个功能。数据是一个对象,其中array
名为users
,您可能想要迭代。
<强> Live Demo 强>
$.each(data.users, function (i, obj) {
$("#placeholder").append('<p>' + obj.firstName + "," + obj.lastName + '</p>');
});