【问题标题】:how to fetch database value in ajax each 5 seconds如何每5秒在ajax中获取数据库值
【发布时间】:2015-08-17 00:23:42
【问题描述】:
我使用 MVC 创建了一个函数来汇总所有数据库记录。现在我需要每 5 秒获取一次这些值。这些值一直在更新,但我无法获取最新值(更新后的值),只能获取页面加载时的值。刚刚结束:我需要使用外部文件来获取总和。
function TotalCosern(){
$GetValores = $this->db->select("SELECT cosern FROM planilha");
$acc = array_shift($GetValores);
foreach ($GetValores as $val) {
foreach ($val as $key => $val) {
$acc[$key] += $val;
}
}
return $acc;
print_r($acc)//print the sum
}
【问题讨论】:
标签:
php
ajax
model-view-controller
【解决方案1】:
将您的 ajax 调用放入一个函数中,并使用 setInterval 每 5 秒执行一次该函数,并将响应附加到您的内容 div 中。
(function polling() {
$.post('total.php', function(data) {
$('#content').append(data);
setTimeout(polling, 1000);
});
})();
【解决方案2】:
你可以使用setInterval函数。
示例(使用get 进行ajax 调用):
function fetchData() {
//change to your url
$.get('/someurl/TotalCosern', function(data) {
//refresh the sum content (or other container that you are using)
$('#sum').html(data);
})
}
//when the page is loaded, do the polling
$(document).ready(function () {
//the time here is in milliseconds
setInterval(fetchData, 5000);
})