我正在使用 jquery ajax 来调用 servlet。它在页面加载期间被调用,并使用 ajax 响应(来自 servlet)填充 div。
我想在单击按钮并重新加载 div 时再次使用此功能。我这里有个问题。所有值都会附加到表中的现有值,而不是重新加载 div。
如何通过替换以前的内容来重新加载此 div?
我的代码(HTML):
<div>
<table id="table1">
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
<tbody>
<!-- Adds the rows dynamically from Jquery AJAX response -->
</tbody>
</table>
</div>
JQuery:
function loadMyTable() {
$.get('CallServlet', {}, function (responseText) {
var response = $.parseJSON(responseText);
$.each(response, function (key, value) {
var row = $("<tr/>")
$('#table1').append(row);
row.append($("<td>" + value.val1 + "</td>"));
row.append($("<td>" + value.val2 + "</td>"));
row.append($("<td>" + value.val3 + "</td>"));
});
$('#table1').dataTable();
});
}
最佳答案
1) 将 Id 提供给您的 Tbody
<tbody id='table1tbody'>
</tbody>
2)更改追加
function loadMyTable() {
$.get('CallServlet', {}, function (responseText) {
var response = $.parseJSON(responseText);
$("#table1tbody").html("");
$.each(response, function (key, value) {
var row="<tr>";
row+="<td>" + value.val1 + "</td>";
row+="<td>" + value.val2 + "</td>";
row+="<td>" + value.val3 + "</td>";
row+="</tr>";
$("#table1tbody").append(row);
});
$('#table1').dataTable();
});
}
关于javascript - 使用 jquery ajax 响应重新加载选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32770929/