javascript - 从加载的 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"}]
谢谢你的帮助!
解决方案
使用 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))
}
推荐阅读
- php - 内联类型注释的状态
- python - Tensorflow:加载一个 .pb 文件,然后将其保存为冻结图问题
- python - Microsoft SQL Server 不会通过 Python 连接
- javascript - express.js,如果我删除下一个参数,错误处理程序将不起作用
- c# - 如何在泛型类中获取属性和值?
- swift - UILabel 有错误的框架。迅速
- python - anaconda 3 升级后使用 anaconda 2
- oauth-2.0 - RingCentral /token API 响应中缺少 Id_token
- python - PyQt4 - 如何禁用所有热键(本机键盘快捷键)
- react-native - 对未计算文件的本机捆绑 sha-1 做出反应(无法从资产 index.android.bundle 加载脚本)