如何检查数据库与PHP和AJAX更新?数据库、PHP、AJAX

2023-09-11 00:36:37 作者:可以惯着你,也可以换了你

我想提出一个聊天框,一切工作正常,除了更新的东西。 我目前刷新页面每隔3秒钟检查任何新的消息,但它肯定会造成服务器巨大的工作量,而且不优雅。

I am making a chat box, everything is working fine, except the update thing. I am currently refreshing the page every 3 sec to check any new messages, but it will surely cause a massive load on server and is not elegant.

我要的是,聊天框将检查只有当数据库更新的新邮件,而不是每3秒

What i want is, chat box will check for new messages only when database is updated, rather than the timer of checking database after every 3 sec

推荐答案

您希望AJAX推送(服务器发送更新客户端时,才会有新的东西)。见一个例子在这里: http://provatosys.com/bid.html

You want AJAX push (server sends update to client only when there's something new). See an example here: http://provatosys.com/bid.html

像这样的阐述来自客户端的请求:

Something like this would elaborate the request from the client:

function sendRequest(uid){
    var xmlhttp;
    var myUserId="";
    myUserId=uid;

    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            displayInChat(xmlhttp.responseText)//do stuff (process response, display message)
        }
    }

    xmlhttp.open("GET","process_request.php?userid="+uid,true);
    xmlhttp.send();

    setTimeout("sendRequest("+uid+")",1000); //poll every second
}

现在要推迟从你的服务器(process_request.php)的答复,直到有什么东西送(使用类似,而(($味精= new_msgs())===假){睡眠(超时);} )后或请求超时和一个新的民意调查是从客户端发送(的setTimeout(sendRequest将(+ UID +),timeoutinmillisecs) ; )。这就是所谓的长轮询和喜欢聊天应用比空响应回答更有效。

Now you want to delay the reply from your server (process_request.php) until there's something to send (using something like while (($msg=new_msgs()) === false) {sleep(timeout);} for example) or the request times out and a new poll is send from the client (setTimeout("sendRequest("+uid+")",timeoutinmillisecs);). This is called Long polling and for applications like chats is more efficient than replying with an empty response.

您可以在这里找到更多信息:简单英寸长轮询"例如code?

You can find more info here: Simple "Long Polling" example code?

在这里:使AJAX调用等待事件在PHP

在这里:彗星(编程)

作为一个非常急需的,更有效的替代长轮询,现在所有主流浏览器都支持的的WebSockets 。 已进入2011年的(建议)标准的地位的 RFC6455(这意味着它已退出草案状态并没有因为任何的变化)。在PHP中最好的实现可能棘轮(据我所知的最最新与标准迄今为止)。下面是关于如何使用它来构建一个网络聊天教程: http://socketo.me/docs/hello - 世界 的

As a very much needed and more efficient alternative to long polling, now all major browsers support websockets. The RFC6455 has entered the status of (proposed) standard in 2011 (which means it has exited draft status and hasn't had any changes since). The best implementation in PHP is probably Ratchet (as far as I know the most up to date with the standard by far). Here is a tutorial on how to build a web chat using it: http://socketo.me/docs/hello-world