[英]ajax response not populating INSIDE html <table> tag
不能完全确定我在哪里出错,但是我希望响应的内容填充在html标签中。 我想首先添加表标签,标题。 然后让函数填充表格标记的内部。 最后关闭桌子。 但是这里有些不对劲。
没有错误正在生成。 所有数据都显示在页面上,但不会显示在表格标签内,因此可以应用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()
表格标签中没有任何响应数据。 相反,它似乎出现在表标签的外面。
而不是多次附加,您应该声明一个变量并向其附加html。 完成附加html之后,您最终应该将字符串附加到div标签。
var content="<table id='ufo-table'>";
content+="<tr><th>Data 1</th><th>Data 2</th><th>Data 3</th></tr>";
for (var i = 0; i < 10; i++) {
content+="<tr><td>" + i + "</td><td>" + response[i].spaceships +
"</td><td>" + response[i].planets + "</td></tr>";
}
content+="</table>";
$('#ufo').append(content);
这将创建一个表并将其附加到#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不会从end标签构造元素。
尽管抽象。 您正在使用DOM元素,而不是原始HTML。 您不能将开始标签附加到一个元素,只能附加另一个元素。
我认为在您的for循环中,您是$("#ufo")
而不是应该使用$("#ufo-table")
来执行此操作,即在表内附加表行和表数据,然后在$("#ufo")
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.