[英]Jquery append and settimeout endless loop
我试图在表中显示我的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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.