首页 > 解决方案 > 从加载的 json 文件生成 HTML 表不起作用

问题描述

我需要从 json 文件生成 HTML 表。加载正常,我可以在 console.log 中看到值,但我不知道如何在其他函数(生成表函数)中传递这些值这是我的代码:

<!DOCTYPE html>
<html lang="fr-CA" dir="ltr">
<head>
  <meta charset="utf-8">
  <title>Tableau de l'inventaire - API JSON</title>
</head>
<body>
  <h2>Voitures en inventaire</h2>

  <table id="myTable">
    <thead>
  <tr>
    <th>No Stock</th>
    <th>Marque</th>
    <th>Modèle</th>
    <th>Année</th>
  </tr>
    </thead>
  </table>
  <button type="button" onclick="loadTable()">Charge Content</button>

  <script type="text/javascript">

  // Loading json file = OK
  function loadXMLDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        // JSON.parse(this.responseText);
        var i = JSON.parse(this.responseText);

        // var x = document.getElementById("myTable").innerHTML = this.responseText

        // console.log(jsonObj);
      }
    };
    xhttp.open("GET", "voituresRecords.json", true);
    xhttp.send();
  }

  // Generate table from json data = Not working
  function loadTable(loadXMLDoc) {
    var x = document.getElementById('myTable');
    for(var i = 1; i < array.length; i++) {
      var newRow = table.insertRow(table.length);
      for(var j = 0; j < array[i].length; j++) {
        var cell = newRow.insertCell(j);
        cell.innerHTML = array[i][j];
      }
    }
  }
</script>
</body>
</html>

这是来自文件的 json 数据:

[{"no_stock":"AC5678","marque":"Hyundai","modele":"Accent","annee":"2006"},
 {"no_stock":"EL5320","marque":"Hyundai","modele":"Elantra","annee":"2018"},
 {"no_stock":"KO4301","marque":"Hyundai","modele":"Kona","annee":"2018"},
 {"no_stock":"TO4210","marque":"Hyundai","modele":"Tucson","annee":"2017"}]

谢谢你的帮助!

标签: javascriptjson

解决方案


使用 fetch 可能会更容易:https ://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

你的代码应该这样

<h2>Voitures en inventaire</h2>

<table id="myTable">
  <thead>
    <tr>
      <th>No Stock</th>
      <th>Marque</th>
      <th>Modèle</th>
      <th>Année</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

<button type="button" onclick="loadTable()">Charge Content</button>
const myTableBody = document.querySelector('#myTable tbody')

function loadTable() {
  fetch('voituresRecords.json')
  .then(resp => resp.json())
  .then(data => {
    data.forEach( info=>{
      let newRow = myTableBody.insertRow()
      newRow.insertCell().textContent = info.no_stock
      newRow.insertCell().textContent = info.marque
      newRow.insertCell().textContent = info.modele
      newRow.insertCell().textContent = info.annee
    })
  })
  .catch(error => console.error(error))
}

推荐阅读