2017-03-09 79 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