I created a code to convert json data to html table using javascript and ajax: (column 1 is text, column 2 is link, column 4 is image link)
Data:
JavaScript
x
6
1
[
2
["Product_1_Title", "www.website1.com", 20, "https://images-na.ssl-images-amazon.com/images/I/81b1roZwACL._AC_SL1500_.jpg"],
3
["Product_2_Title", "www.website2.com", 50, "https://images-na.ssl-images-amazon.com/images/I/71W1KvLH3sL._AC_SL1500_.jpg"],
4
5
]
6
This is the code, it work well, but on the table result, I want to hide column 2 and put the link in column 2 in an anchor in column 1 so the Title become clickable link, and put the image link on column 4 into src so the picture shown on the cell.
JavaScript
1
63
63
1
<body>
2
3
<table id="tab">
4
<thead>
5
<tr>
6
<th>column_1</th>
7
<th>column_2_link</th>
8
<th>column_3</th>
9
<th>column_4_link</th>
10
</tr>
11
</thead>
12
<tbody>
13
</tbody>
14
</table>
15
16
<script type="text/javascript">
17
const TabBody = document.querySelector("#tab > tbody")
18
function loadData() {
19
const request = new XMLHttpRequest();
20
request.open("get", "rows.json");
21
request.onload = () => {
22
try {
23
const json = JSON.parse(request.responseText);
24
populateTable(json);
25
} catch (e) {
26
console.warn("error");
27
}
28
};
29
30
request.send();
31
}
32
function populateTable(json){
33
34
while(TabBody.firstChild){TabBody.removeChild(TabBody.firstChild);}
35
36
json.forEach((row) => {
37
const tr = document.createElement("tr");
38
39
40
row.forEach((cell) => {
41
const td = document.createElement("td");
42
43
// I tried this and it put the link text inside <a>
44
// td.innerHTML = /.com//g.test(cell)
45
// ? `<a href="https://${cell}">${cell}</a>`
46
// : cell;
47
48
// and tried this and it put the link text inside <img>
49
td.innerHTML = /alicdn.com/g.test(cell)
50
? `<img src="https://${cell}" class="img-fluid"/>`
51
: cell;
52
53
tr.appendChild(td);})
54
55
TabBody.appendChild(tr);
56
})
57
}
58
document.addEventListener("DOMContentLoaded", () => { loadData();})
59
</script>
60
61
</body>
62
63
Advertisement
Answer
Instead of iterating through the cells, if you know the position of the columns in the array you can hard code the row.
JavaScript
1
17
17
1
function populateTable(json){
2
while(TabBody.firstChild){TabBody.removeChild(TabBody.firstChild);}
3
json.forEach((row) => {
4
const tr = document.createElement("tr");
5
let td = document.createElement("td");
6
td.innerHTML = `<a href='${row[1]}'>${row[0]}</a>`
7
tr.appendChild(td);
8
td = document.createElement("td");
9
td.innerHTML = row[2];
10
tr.appendChild(td);
11
td = document.createElement("td");
12
td.innerHTML = `<img src="https://${row[3]}" class="img-fluid"/>`;
13
tr.appendChild(td);
14
TabBody.appendChild(tr);
15
})
16
}
17
And take out the second column in the table instead of hiding it
JavaScript
1
8
1
<thead>
2
<tr>
3
<th>column_1</th>
4
<th>column_2</th>
5
<th>column_3_link</th>
6
</tr>
7
</thead>
8