<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
table, td, th {
border: 1px solid black;
}
table {
border-collapse: collapse;
width: 100%;
}
td {
height: 50px;
vertical-align: bottom;
}
</style>
</head>
<body>
<table id =101>
<tr>
<th>id</th>
<th>name</th>
<th>category</th>
<th>color</th>
</tr>
<div>
</div>
</table>
<script>
var url = "http://34.201.147.118:3001/getAllData";
var xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
console.log(users)
if (xhr.readyState == 4 && xhr.status == "200") {
var obj= users
console.table(obj);
var tbl=$("#101").attr("id","mytable");//The attr() method set the id attribute to mytable this method is used to return the attribute value, it returns the value of the FIRST matched element.When this method is used to set attribute values,
$("#div1").append(tbl);
for(var i=0;i<obj.length;i++)
{
console.log(obj.length)
var tr="<tr>";
var td1="<td>"+obj[i]["id"]+"</td>";
var td2="<td>"+obj[i]["name"]+"</td>";
var td3="<td>"+obj[i]["category"]+"</td>";
var td4 ="<td>"+obj[i]["color"]+"</td></tr>";
$("#mytable").append(tr+td1+td2+td3+td4);
}
console.table(users);
} else {
console.error(users);
}
}
</script>
</body>
</html>
- 我在我的 html 页面上创建了一个表,我想调用我的 rest api 并获取 数据 .from rest api 并解析为我在 ui 中创建的表
- 但我想我的代码没有进入 onload 函数 哪里出错了请指正
- 如果表中的任何字段留空,我想打印 NA
- 请提出任何代码更改
- 提前致谢
最佳答案
尝试这段代码并在循环中更新您的参数。
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>
<style>
table, td, th {
border: 1px solid black;
}
table {
border-collapse: collapse;
width: 100%;
}
td {
height: 50px;
vertical-align: bottom;
}
</style>
</head>
<body>
<table id='mytable'>
<tr>
<th>id</th>
<th>name</th>
<th>category</th>
<th>color</th>
</tr>
<div>
</div>
</table>
<script>
$(document).ready(function(){
var url = "http://34.201.147.118:3001/getAllData";
$.getJSON(url, function( data ) {
var obj = data['AllData'];
for(var i=0;i<obj.length;i++)
{
var tr ="<tr>"+
"<td>"+obj[i]["id"]+"</td>"+
"<td>"+obj[i]["name"]+"</td>"+
"<td>"+obj[i]["category"]+"</td>"+
"<td>"+obj[i]["color"]+"</td></tr>";
$("#mytable").append(tr);
}
});
});
</script>
</body>
</html>
关于javascript - 从 rest api 调用数据并解析到 ui 中的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50771214/