如何在我的HTML网页中使用JSON文件

时间:2016-12-28 06:14:38

标签: javascript html json ajax

我正在尝试在JSON页面中实施以下HTML文件。

<html>
  <head>
    <title> test get</title>

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">

      <script>
        $(function() {
            $.getJSON('json.json',function(data) {
                $.each(data.quotes,function(key,value) {
                    alert( key+ "said by "+value);
                });
            });
        });
    </script>

  </head>

  <body>
  </body>

</html>

以下是我正在处理的JSON

{
    "quotes": {
        "hey there":"randomguy1",
        "wassup":"randomguy2",
        "coool":"randomguy3"
    }
}

我在stackoverflow上检查了不同的教程和类似的问题仍然无法弄清楚错误。

2 个答案:

答案 0 :(得分:2)

只需修正您的script代码,

必须关闭<script ...jquery>标记。

<html>
<head>
    <title>test get</title>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

  <script>
    $(function () {
        $.getJSON('json.json', function (data)
        {
            $.each(data.quotes, function (key, value) {
                alert(key + "said by " + value);
            });
        });

    });
  </script>

  </head>

  <body> </body>
</html>

答案 1 :(得分:0)

您可以通过其他方式实现目标。使用 ajax 加载文件内容并将其解析为 json

$.ajax({
            url : "helloworld.json",
            success : function (data) {
                //TODO parse string to json
            }
        });