簡體   English   中英

嘗試使用 HTML 中的 JS 腳本讀取 JSON 文件

[英]Trying to read a JSON file with a JS script in HTML

我正在嘗試使用我的 json 文件busesNotArrived.json並將其內容放在<p>中,但是它不起作用,並且 JSON 文件中的數據不顯示,我的代碼在這里:

<p>Buses Not Arrived:<br><br><span id="output"></p>

<script>
  const fs = require('fs')
  fs.readFile('json/busesNotArrived.json', 'utf8', (err, jsonString) => {
      if (err) {
          alert('Error reading Database:', err)
          return
      }
      try {
          const bus = JSON.parse(jsonString)
          alert("Bus address is:", bus.busNumber)
          document.getElementById('output').innerHTML = bus.BusNumber;
  } catch(err) {
          alert('Error parsing JSON string:', err)
      }
  })
</script>

在我的 JSON 文件中,存儲了以下內容:

{
    "busRoute": 123123,
    "busNumber": 123123
}

Javascript is not the same as node.js require() is not a part of JavaScript standard and is not supported by browsers out of the box, it is the node.js module system.

您可能需要直接包含模塊; 某些模塊可能無法在瀏覽器沙箱上下文中運行。

此外, http://browserify.org/等工具也可能有用。

並且請把錯誤信息也。

Well, I eventually figured it out, so like what @Ronnel said, you cannot use require() because that is node.js and not javascript, so you would have to use the fetch() api to get the .json file.

對於任何想查看代碼的人,這里是:

<div id="myData" class='absolute1' onclick='notArrived()'><strong><u>Not Yet Arrived</u></strong><br><br></div>

<script>
        fetch('json/busesNotArrived.json')
              .then(function (response) {
                  return response.json();
              })
              .then(function (data) {
                  appendData(data);
              })
              .catch(function (err) {
                  console.log('error: ' + err);
              });
          function appendData(data) {
              var mainContainer = document.getElementById("myData");
              for (var i = 0; i < data.length; i++) {
                  var div = document.createElement("div");
                  div.innerHTML = 'Bus Number: ' + data[i].busNumber + "<br>" + 'Bus Route:' + ' ' + data[i].busRoute + "<br><br>";
                  mainContainer.appendChild(div);
              }
          }

</script>

|| 對縮進感到抱歉:P ||

此外,這是.json文件中的內容,因此您可以處理它:

[
    {
        "id": "1",
        "busNumber": "4024",
        "busRoute": "44444"
    },
    {
        "id": "2",
        "busNumber": "4044",
        "busRoute": "4444"
    },
    {
        "id": "3",
        "busNumber": "5024",
        "busRoute": "55555"
    }
]

祝你好運!

如果您想要更多解釋,這里是我獲得代碼的地方:

https://howtocreateapps.com/fetch-and-display-json-html-javascript/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM