$(document).ready(function(){
setInterval(function(){
$.ajax({ url: "getLiveData.php",
success: function(result){
$.each(result, function(i, result){
var t = $("table#insideTable");
t.append('<tr><td>' + result.carNo + '</td><td>' +
result.carSpeed + '</td></tr>');
});
},
dataType: "json"
});
}, 600000);
});
您好,我试图使用上面的代码每10分钟更新一次车速。
- 上午10:20的数据-----
+-------+-------+
|car |speed |
+-------+-------+
|1 |170 kph|
+-------+-------+
|2 |150 kph|
+-------+-------+
|3 |190 kph|
+-------+-------+
- 上午10:30的数据-----
+-------+-------+
|car |speed |
+-------+-------+
|1 |180 kph|
+-------+-------+
|2 |155 kph|
+-------+-------+
|3 |174 kph|
+-------+-------+
然而,在运行代码之后,从两个时间点获得的结果全部显示,一个接一个(见下文)。
+-------+-------+
|car |speed |
+-------+-------+
|1 |170 kph|
+-------+-------+
|2 |150 kph|
+-------+-------+
|3 |190 kph|
+-------+-------+
|1 |180 kph|
+-------+-------+
|2 |155 kph|
+-------+-------+
|3 |174 kph|
+-------+-------+
我真正想要的是将以后的新数据替换为当前的数据。
+-------+-------+
|car |speed |
+-------+-------+
|1 |180 kph|
+-------+-------+
|2 |155 kph|
+-------+-------+
|3 |174 kph|
+-------+-------+
任何人都可以帮助我吗?
非常感谢!
答案 0 :(得分:2)
您想使用.html()
功能代替.append()
:
变化:
success: function(result){
$.each(result, function(i, result){
var t = $("table#insideTable");
t.append('<tr><td>' + result.carNo + '</td><td>' + result.carSpeed + '</td></tr>');
});
}
要:
success: function(result){
//create an output variable that will be added to the DOM when we're finished
var output = '';
//iterate through the results of the AJAX request
$.each(result, function(i, result){
//add a row to the output variable
output += '<tr><td>' + result.carNo + '</td><td>' + result.carSpeed + '</td></tr>';
});
//add the output to the DOM, notice that since we are only adding nodes to the DOM once this creates less CPU overhead than appending each row separately (we also save overhead by not selecting the table element during each iteration of the $.each() loop)
$("#insideTable").html(output);
}
这将替换表元素中的HTML而不是附加到它。以下是使用.html()
与.append()
:http://jsfiddle.net/jasper/TKaVF/
以下是.html()
的文档:http://api.jquery.com/html
从侧面说明,添加table
后,它不会使你的选择器更快,因为你正在查找一个ID(这本身就很快)。
var t = $("table#insideTable");
会更快:
var t = $("#insideTable");
答案 1 :(得分:1)
工作示例:http://jsfiddle.net/manseuk/mnRTf/
将您的成功方法更改为:
$('#tablecontainerdiv').html('<table>');
$.each(result, function(i, result){
$("#tablecontainerdiv table").append('<tr><td>' + result.carNo + '</td><td>' +
result.carSpeed + '</td></tr>');
});
$('#tablecontainerdiv').append('</table>');
其中tablecontainerdiv
是表格所包含的div,例如:
<div id="tablecontainerdiv">
<table>
//your data here
</table>
</div>
新代码将用新数据替换旧表
答案 2 :(得分:0)
在添加新行之前,只需清空表格:
success: function(result){
var t = $("table#insideTable"); // moved outside the loop
t.empty(); // remove contents of the element
$.each(result, function(i, result){
t.append('<tr><td>' + result.carNo + '</td><td>' +
result.carSpeed + '</td></tr>');
});
}