简体   繁体   English

jQuery追加和设置超时无限循环

[英]Jquery append and settimeout endless loop

I'm try to display my json data in a table and refresh it periodically (to check if any new entries were added). 我试图在表中显示我的json数据并定期刷新(以检查是否添加了任何新条目)。 However, I ended up getting stuck in an endless loop. 但是,我最终陷入了无休止的循环。 The setTimeOut will keep appending old entries. setTimeOut将继续追加旧条目。 Can someone help me figure this out? 有人可以帮我解决这个问题吗?

js fiddle link: http://jsfiddle.net/eprte2m6/ js小提琴链接: http//jsfiddle.net/eprte2m6/

js 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 test.json

[{
  "type":"Tablet", 
  "date":"02/03/14", 
},
{
  "type":"Tablet", 
  "date":"02/05/14", 
}]

html HTML

<table class="table" id="monitor1">
      <thead>
        <tr>
          <th>type</th>
          <th>Date</th>
        </tr>
      </thead>
</table>      

There are two options 有两种选择

1) You can clear the table before appending like bellow. 1)您可以像波纹管一样清除表格。

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

after append the data to table 将数据追加到表后

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

DEMO DEMO

2) You can have a variable which will contain your previous JSONdata and at the time of response you can check, if both data are not same get the difference between both in another JSON. 2)您可以有一个变量,其中将包含您以前的JSONdata并且在响应时可以检查是否两个数据都不相同,从而获得另一个JSON之间的差异。 And update your table with that difference. 并用这种差异更新表。

不要使用.append ,而应使用.html如下所示:

$('#monitor1').html(trHTML);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM