2017-03-09 80 views
0

我試圖用jQuery的內容創建一個動態表格。此外,我已經爲了啓用setTimeout用於以來我用我的setTimeout動態表是越來越重複刷新和更新的數據在html page.`settimeout在jquery中動態創建表格

$(document).ready(function update_data() { 
 
    $.ajax({ 
 
    dataType: "json", 
 
    url: "/wirelessSensor/dag", 
 
    success: updateForData, 
 
    error: errorOnAjax 
 
    }); 
 

 
    setTimeout(function() { 
 
    update_data(); 
 
    }, 5000); 
 

 
}); 
 

 
function updateForData(data) { 
 
    // Updates DAG 
 
    console.log("Wirless nodes details"); 
 
    var hasData = true; 
 

 
    if (data.result && data.result && data.result == "none") { 
 
    console.log('No data in result'); 
 
    hasData = false; 
 
    } else if (!data.devices || !data.status) { 
 
    console.log('Devices not found in result'); 
 
    hasData = false; 
 
    } 
 

 
    if (hasData) { 
 

 
    console.log('Creating Table'); 
 

 
    var trHTML = ''; 
 
    $.each(data.devices, function(index) { 
 

 
     trHTML += "<tr><td>" + data.devices[index] + "</td><td>" + data.lifetime[index] + "</td><td>" + data.status[index] + "</td></tr>"; 
 
    }); 
 

 
    $("#location").append(trHTML); 
 
    } 
 
} 
 

 

 
function errorOnAjax(jqxhr, status, errorstr) { 
 
    var errText = (errorstr == null) ? 
 
    '' : ', error: ' + errorstr; 
 
    console.log('Ajax error: ' + status + errText); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table id="location" border='1' width='100%'> 
 
    <tr> 
 
    <th align='center'> Devices </th> 
 
    <th align='center'> Lifetime </th> 
 
    <th align='center'> Status </th> 
 
    </tr> 
 
</table>

這裏。已經存在的條目已被重複。我怎樣才能避免這種情況?

回答

0

您可以重構您的HTML以包含<thead><tbody>元素,並將<tbody>的內容設置爲結果(而不是將結果附加到可能已存在的條目)。

<table id="location" border='1' width='100%'> 
    <thead> 
    <tr> 
     <th align='center'> Devices </th> 
     <th align='center'> Lifetime </th> 
     <th align='center'> Status </th> 
    </tr> 
    </thead> 
    <tbody id="location-content"></tbody> 
</table> 

然後做$("#location-content").html(trHTML);(注:html而不是append,摧毀舊的結果,而不是讓他們)

+0

謝謝:)。但是現在我錯過了我的標題。我如何將這些包含在我的表格中? – NTP

+0

@NTP啊,在這種情況下,請確保您的標題與表格主體不在同一個元素中。我建議使用''和''(然後將結果寫入'')。我編輯了答案。 – apsillers

+0

你釘了它! – NTP