我是使用 JSON 的新手,我正在尝试做一些我确信非常简单的事情,但我已经寻找了一段时间,但尚未找到正确的方法。 我有两个文件,一个 html 页面和一个 json 文件,其中包含一个数组。 JSON 文件的内容如下所示:
[
{ "name": "EXAMPLE1",
"description": "this is a sample description"},
{ "name": "EXAMPLE2",
"description": "This is a second sample description"}
]
我正在尝试获取数组元素并将它们显示在 html 页面上,其中“名称”是标题 (h1),“描述”是段落 (p)。
下面是我目前在 html 文件中的代码,如果我完全误解了如何进行此操作,我不会感到惊讶:
<!DOCTYPE html>
<html>
<head>
<title>Json Arrays</title>
</head>
<body>
</body>
<script>
$(document).ready(function(){
$.getJSON("testarray.json", function(data){
$.each(data, function)(){
$("body").append("<h1>"+this['name']+<br>"</h1>""<p>"+this['description']+<br>"</p>");
}
}
}
</script>
</html>
如有任何建议,我们将不胜感激。
最佳答案
你必须正确解析它。这是我调整的代码。
<!DOCTYPE html>
<html>
<head>
<title>Json Arrays</title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
</body>
<script>
$(document).ready(function(){
$.getJSON("testarray.json", function(data){
console.log(data);
$.each(data, function(i, field){
$("body").append("<h1>"+field.name+"<br></h1><p>"+field.description+"<br></p>");
});
})
});
</script>
</html>
在每个之后,一切都将是对象,所以只需使用 field.name
关于javascript - Json数组元素到html页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23692095/