不太确定我哪里出错了,但我希望响应的内容填充到 html 标签内。我想首先附加表格标签,标题。然后让函数填充表标签的内部。最后关闭 table 。但这里有些不对劲。
没有生成任何错误。所有数据都呈现在页面上,但不在表格标签内,以便可以应用 CSS 类。
HTML 正文
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="./assets/javascript/getdata.js"></script>
<link rel="stylesheet" href="./assets/css/style.css">
</head>
<body>
<div class="page-header">
<h1>Data Table</h1>
</div>
<div id="ufo">ajax_response_goes_here</div>
</body>
</html>
JavaScript
function displayrecipes() {
$.ajax({
type: "GET",
url: "https://data_url",
dataType: "json"
})
.done(function (response) {
$('#ufo').append("<table id='ufo-table'>")
$('#ufo').append("<tr><th>Data 1</th><th>Data 2</th><th>Data 3</th></tr>")
for (var i = 0; i < 10; i++) {
$('#ufo').append("<tr><td>" + i + "</td><td>" + response[i].spaceships +
"</td><td>" + response[i].planets + "</td></tr>")
}
$('#ufo').append("</table>")
})
}
displayrecipes()
表选项卡中没有任何响应数据。相反,它似乎出现在表格标签之外。
最佳答案
这会创建一个表并将其附加到#ufo
<小时/>$('#ufo').append("<table id='ufo-table'>")
这将创建一个表格行并将其附加到#ufo
$('#ufo').append("<tr><th>Data 1</th><th>Data 2</th><th>Data 3</th></tr>")
如果您希望表格行位于表格内,则必须将其附加到表格而不是div。
<小时/>$('#ufo').append("</table>")
这没有任何作用。 jQuery 不会从结束标记构造元素。
尽管是抽象的。您正在使用 DOM 元素,而不是原始 HTML。您不能将开始标记附加到一个元素,只能附加到另一个元素。
关于javascript - ajax 响应未填充 INSIDE html <table> 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54230577/