簡體   English   中英

jQuery追加和設置超時無限循環

[英]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);

DEMO

2)您可以有一個變量,其中將包含您以前的JSONdata並且在響應時可以檢查是否兩個數據都不相同,從而獲得另一個JSON之間的差異。 並用這種差異更新表。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM