javascript - 从rest api获取数据并在html页面中以table的形式打印出来
问题描述
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
var url = "";
var xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "200") {
console.log(users);
console.log(typeof users)
console.table(users);
} else {
console.error(users);
}
}
xhr.send(null);
</script>
</body>
</html>
我想获取restapi数据并在我的HTML页面而不是控制台上以表格的形式打印。从脚本标签出来后,我的对象的范围正在丢失帮助我在html页面上打印数据提前谢谢
解决方案
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<table>
<tr id="user"></tr>
</table>
<script>
var url = "";
var xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "200") {
console.log(users);
for(var i = 0; i < user.length;i++){
var node = document.createElement("td");
var textnode = document.createTextNode(user[i]);
node.appendChild(textnode);
document.getElementById("user").appendChild(node);
}
}
xhr.send(null);
</script>
</body>
</html>
首先,您的响应数据应该以数组形式出现,然后使用 for 循环迭代响应数据,在 HTML 中创建为 tr 提供 id。在 for 循环中创建一个节点作为 TD 并附加您的 TD,最后调用该 ID。
推荐阅读
- c++ - 在现代 CMake 中将接口库添加为 SYSTEM
- c# - .NET System.Security.Cryptographic 中来自 CAPICOM 的 AES 解密
- jmeter - 如何根据命令行传入的Environment参数执行Jmeter脚本
- qt - 如何将 QTableWidget + QComboBox 放在一起,如果值从同一行的 QComboBox 更改,如何访问特定行
- r - 如何使用“应用”自动将标题放在一系列生成的图上
- javascript - 从 api 获取数据并将其传递给 React 中的状态
- c# - 包括 NGravatar 会导致 OData.Core dll 找不到(并使用更高版本)
- html - 如何在可内容编辑的 HTML 元素中的两个字符之间插入零宽度线
- java - 使用 Android Studio 的 webview 时无法在 HTML 文件中使用相机
- node.js - 未定义变量:运行 npm 开发服务器时的“$font-weight-bolder”