我尝试在表中显示我的json数据,并定期刷新它(检查是否添加了任何新条目)。然而,我最终陷入了一个无休止的循环。setTimeOut将继续追加旧条目。有人能帮我弄清楚吗?
js小提琴链接:http://jsfiddle.net/eprte2m6/
js
<script>
(function worker() {
$.ajax({
url: 'test.json',
type: 'POST',
data: 'json',
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr class="success"><td>' + item.type + '</td><td>' + item.date + '</td></tr>';
});
$('#monitor1').append(trHTML);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 5000);
}
});
})();
</script>
test.json
[{
"type":"Tablet",
"date":"02/03/14",
},
{
"type":"Tablet",
"date":"02/05/14",
}]
html
<table class="table" id="monitor1">
<thead>
<tr>
<th>type</th>
<th>Date</th>
</tr>
</thead>
</table>
有两个选项
1)您可以在如下所示追加之前清除表格。
$('#monitor1 tbody').empty();
将数据附加到表之后
$('#monitor1').append(trHTML);
演示
2)您可以有一个变量,该变量将包含您以前的JSONdata
,在响应时您可以检查,如果两个数据不相同,则在另一个JSON中获取两者之间的差异。并用这个差异更新您的表格。
不要使用.append
,而是使用.html
,如下所示:
$('#monitor1').html(trHTML);