根据数据库输入更改html中的值

时间:2015-08-10 13:54:13

标签: php jquery html

我正在尝试开发一个应用程序,其中实时检测数据库中的更改非常重要...我已经设计了一种方法来通过运行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);

});

请帮忙!

1 个答案:

答案 0 :(得分:2)

对我来说,最好的解决方案是

  • 在服务器端编写标识更改的服务
  • 在客户端上,优先使用websockets检查此服务(如果您不能使用websockets,则检查ajax),如果有更改,请下载,这样您就可以获得经济性和速度更强的功能

示例已更新

使用ajax

function downloadUpdates(){
    setTimeout(function(){
        $.ajax({
            url: 'have-changes.php'
            success:function(response){
                if(response == 'yes'){
                    // ok, let`s download the changes
                    ...

                    // after download updates let`s start new updates check (after success ajax method of the update code)
                    downloadUpdates(); 
                }else{
                    downloadUpdates();
                }
            }
        });
    }, 3000);
}
downloadUpdates();

使用websockets

var exampleSocket = new WebSocket("ws://www.example.com/changesServer");
exampleSocket.onmessage = function(event) {
  if(event.data != "no"){
        // ok here are the changes
        $("body").html(event.data);
    }
}
exampleSocket.onopen = function (event) {
    // testing it
    setInterval(function(){
        exampleSocket.send("have changes?");
    }, 3000)
}

Here (I have tested it )Here一些如何在php上使用websocokets的例子,问题是你需要shell访问