Jquery追加和settimeout无限循环

时间:2014-09-15 01:47:04

标签: javascript jquery json

我尝试在表中显示我的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>      

2 个答案:

答案 0 :(得分:1)

有两个选项

1)您可以在追加下面之前清除表格。

$('#monitor1 tbody').empty();

将数据附加到表

之后
$('#monitor1').append(trHTML);

DEMO

2)您可以拥有一个包含之前JSONdata的变量,并且在回复时您可以检查,如果两个数据不相同,则在另一个中获取两者之间的差异JSON。并用这种差异更新你的表格。

答案 1 :(得分:0)

请勿使用.append,而是使用.html,如下所示:

$('#monitor1').html(trHTML);
相关问题