【问题标题】:change values in html based on database input根据数据库输入更改 html 中的值
【发布时间】: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);

});

请帮忙!

【问题讨论】:

标签: php jquery html


【解决方案1】:

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

  • 在服务器端编写一个识别更改的服务
  • 在客户端,优先使用websockets检查此服务(如果不能使用websocket,则使用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();

使用网络套接字

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访问权限

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    相关资源
    最近更新 更多