如何使用jQuery在列表中显示json数据?
$(document).ready(function() {
$.getJSON('example.json', function(data) {
$.each(data.example, function(key, value) {
var output="";
output="<li>" + data.example[key].name + "</li>";
$('#example').append(output);
});
});
}
&#13;
这似乎没有显示任何内容。
答案 0 :(得分:1)
$(document).ready(function() {
$.getJSON('example.json', function(data) {
var output = '';
$.each(data.example, function(key, value) {
output += '<li>' + value.name + '</li>';
});
$('#example').html(output); // <ul id="example"></ul>
});
});
更新:使用JSON文件
{
"example": [
{
"name": "Dr. Sammie Boyer",
"email": "Lavonne.Kiehn@hotmail.com"
},
{
"name": "Eladio Beier",
"email": "Lavonne.Kiehn@hotmail.com"
},
{
"name": "Hilton Borer",
"email": "Reva.Goyette@yahoo.com"
}
]
}
答案 1 :(得分:0)
您有几个语法错误。每个函数中的逗号都在错误的位置,并且没有关闭);在末尾。下面的代码应该可以正常工作......
$(document).ready(function() {
$.getJSON('example.json', function(data) {
$.each(data.example, function(key, value) {
var output="";
output="<li>" + data.example[key].name + "</li>";
$('#example').append(output);
});
});
});
答案 2 :(得分:0)
这是我的看法。
您有多个语法错误(很难看到,因为代码格式不正确) - 格式化代码可以帮助您查看这些错误。
注意:我避免进行AJAX调用以获取循环解析示例的JSON数据。
$(document).ready(function() {
var data = {
"example": [{
"name": "Dr. Sammie Boyer"
}, {
"name": "Eladio Beier",
"email": "Lavonne.Kiehn@hotmail.com"
}, {
"name": "Hilton Borer",
"email": "Reva.Goyette@yahoo.com"
}]
};
// we don't have to get the json in an AJAX call for this demo
// $.getJSON('example.json', function(data) {
var output = "<ul>";
$.each(data.example, function(key, value) {
output += "<li>" + value.name + "</li>";
});
output += "</ul>";
$('#example').append(output);;
// });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example"></div>
&#13;