【发布时间】:2021-06-10 00:34:17
【问题描述】:
我正在使用 ajax 将 json 数据加载到 html 表中。我想出了一种使用特定 json 结构的方法,但不确定如何使用不同格式的 json 来实现。
这是我正在使用的 javascript:
let myArray = [];
$.ajax({
method: "GET",
url: "https://chrisjschreiner.github.io/data/conjugations.json",
success: function (response) {
myArray = response;
buildTable(myArray);
console.log(myArray);
},
});
buildTable = (data) => {
let table = document.getElementById("myTable");
for (let i = 0; i < data.length; i++) {
let row = `<tr>
<td>${data[i].personal_pronoun}</td>
<td>${data[i].conjugation}</td>
</tr>`;
table.innerHTML += row;
}
};
我使用的json数据:
[
{
"personal_pronoun": "Yo",
"conjugation": "abandono"
},
{
"personal_pronoun": "Tú",
"conjugation": "abandonas"
},
{
"personal_pronoun": "Él/Ella/Usted",
"conjugation": "abandona"
},
{
"personal_pronoun": "Nosotros",
"conjugation": "abandonamos"
},
{
"personal_pronoun": "Vosotros",
"conjugation": "abandonáis"
},
{
"personal_pronoun": "Ellos/Ellas/Ustedes",
"conjugation": "abandonan"
}
]
HTML:
<table
class="
table table-striped table-bordered
mb-sm
table-text-color
"
>
<thead>
<tr>
<th>PERSONAL PRONOUN</th>
<th>CONJUGATION</th>
</tr>
</thead>
<tbody id="myTable"></tbody>
</table>
以及由此生成的表格:
我怎样才能得到相同的结果,但使用这样的 json 结构?
{
"Yo": "abordo",
"Tú": "abordas",
"Él/Ella/Usted": "aborda",
"Nosotros": "abordamos",
"Vosotros": "abordáis",
"Ellos/Ellas/Ustedes": "abordan"
}
【问题讨论】:
-
对象 (不是类数组对象) 没有长度。请改用
for in或for of循环。
标签: javascript json ajax