简体   繁体   English

如何在网页上显示.json文件<script> tag?

[英]How to display .json file on webpage when it's in a <script> tag?

Is there a way to manipulate and display the data in the file without using fetch?有没有办法在不使用 fetch 的情况下操作和显示文件中的数据? In addition, can I store the json file in a variable and iterate through it?另外,我可以将json文件存储在一个变量中并遍历它吗? It just seems that for a local file there would be a simpler method of working with/displaying the data...似乎对于本地文件,会有一种更简单的方法来处理/显示数据......

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <link rel="stylesheet" href ="styles.css">
    <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>
    <script src="main.js"></script>
    <script src="animals.json"></script> <!-- added json file-->
</head>
<body>

<div class ="sampleDiv"></div>
</div>
    
</body>
</html>

json file json文件

[
    {
      "name": "Whiskers",
      "species" : "cat",
      "foods": {
        "likes": ["celery", "strawberries"],
        "dislikes": ["carrots"]
      }
    },
    {
      "name": "Woof",
      "species" : "dog",
      "foods": {
        "likes": ["dog food"],
        "dislikes": ["cat food"]
      }
    },
    {
      "name": "Fluffy",
      "species" : "cat",
      "foods": {
        "likes": ["canned food"],
        "dislikes": ["dry food"]
      }
    }
  ]

<script> elements are for loading JavaScript, not JSON. <script>元素用于加载 JavaScript,而不是JSON。

<script src="animals.json"></script> is just going to cause the browser to throw a CORB error when it doesn't get the content-type it is expecting. <script src="animals.json"></script>只会导致浏览器在没有获得预期的内容类型时抛出CORB 错误

Use the fetch API to load the JSON instead.请改用fetch API 来加载 JSON。

fetch("animals.json")
    .then(response => response.json())
    .then(data => {
        // Work with your data here
    });

是的,您可以将 JSON 文件放入 js 文件中,并解析const yourJSON = JSON.parse(/*paste your entire JSON*/)然后将 js 文件添加到 script 标签中,以便您可以访问其他 js 文件中的 yourJSON 变量.

You cannot load .json files as scripts.您不能将 .json 文件作为脚本加载。 You'll need JavaScript code and an HTTP request to load it.您需要 JavaScript 代码和 HTTP 请求来加载它。 This can be done easily by fetch() , but if you're just looking for an alternative, you can use jQuery's $.getJSON :这可以通过fetch()轻松完成,但如果您只是在寻找替代方案,您可以使用 jQuery 的$.getJSON

$.getJSON('animals.json', function(obj) {
    document.getElementsByClassName('sampleDiv')[0].innerHTML = JSON.stringify(obj);
});

In my opinion, the most elegant way to do it is with fetch() .在我看来,最优雅的方法是使用fetch() Dumping the whole json in the JavaScript code and using JSON.parse makes everything extremely unmaintainable and using jQuery is overkill, too.将整个 json 转储到 JavaScript 代码中并使用 JSON.parse 会使一切都变得非常难以维护,并且使用 jQuery 也太过分了。

You cannot fetch local json using pure js, for this purpose use a node web server.您不能使用纯 js 获取本地 json,为此请使用节点 Web 服务器。 If you just want to use your data without any need of mutation, you can just create a data.json file containing your animals.如果你只想使用你的数据而不需要任何突变,你可以创建一个包含你的动物的data.json文件。

const animals = [
    // Your animals here
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM