javascript - Json数组元素到html页面

标签 javascript html json

我是使用 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/

相关文章:

javascript - 防止用户在javascript中输入小数点前超过3个数字

javascript - 如何在 .then() 链中访问之前的 promise 结果?

javascript - 滚动在 chrome 中的 svg 异物内不起作用

html - 使用 CSS 和 spritesheet 中的多个图像设计按钮样式

json - U-SQL - 从 json-array 中提取数据

javascript - 借助谷歌图表获取 'On' 和 'Off status' 的时间序列图

javascript - 使用 Jquery 更改文本字符串

html - 在文本框中跳格

java - 创建 JSONArray 时出现 NullPointerException

javascript - 统计推特搜索API返回的页面数