【发布时间】:2015-11-02 11:31:04
【问题描述】:
我正在尝试开发一个应用程序,其中实时检测数据库中的更改非常重要。我现在设计了一种方法来检测更改,通过运行 ajax 函数并每 3 秒刷新一次页面,但这根本不是很有效,而且在高压力水平上它似乎不是一个有效的解决方案。
有没有什么方法可以检测数据库中是否发生了某些更改而无需刷新页面?附上示例代码。我使用 php 作为我的服务器端语言,以 html/css 作为前端。
$(document).ready(function() {
$('#div-unassigned-request-list').load("atc_unassigned_request_list.php");
$('#div-driver-list').load("atc_driver_list.php");
$('#div-assigned-request-list').load("atc_assigned_request_list.php");
$('#div-live-trip-list').load("atc_live_trip_list.php");
setInterval(function() {
$.ajax({url:"../methods/method_get_current_time.php",success:function(result){
$("#time").html(result);
}});
}, 1000)
setInterval( function() {
$.ajax({url:"atc_unassigned_request_list.php",success:function(result){
$("#div-unassigned-request-list").html(result);
}});
$.ajax({url:"atc_driver_list.php",success:function(result){
$("#div-driver-list").html(result);
}});
$.ajax({url:"atc_assigned_request_list.php",success:function(result){
$("#div-assigned-request-list").html(result);
}});
} ,2000);
});
请帮忙!
【问题讨论】:
-
看看
websocket-protocol!有了它,您可以在 db 更改时将更新从服务器推送到浏览器。 -
如果浏览器兼容性不是大问题,您也可以使用
Server Sent Events。阅读这些链接-> w3schools.com/html/html5_serversentevents.asp & developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/…