简体   繁体   English

数据库更新时如何向客户端发送警报,例如Facebook聊天

[英]How to send alert to client when database is updated, like facebook chat

I want to send alert to client who is using the website only when saome field gets updated. 我想仅在更新saome字段时向使用网站的客户端发送警报。 i know how to regularly check for database updations with silent ajax calls. 我知道如何使用无提示Ajax调用定期检查数据库更新。 I only want to trigger an ajax call when there is information updated. 我只想在更新信息时触发ajax调用。 In other Words, the mysql server will send an alert to client that some table row is changed so that the client will trigger the ajax call and the info can be retrieved. 换句话说,mysql服务器将向客户端发送一条警报,告知某些表行已更改,以便客户端将触发ajax调用,并且可以检索信息。

You can use websockets with PHP. 您可以将websockets与PHP结合使用。 Take a look at Thruway . 看一下Thruway Thruway uses WAMP which supports a publish and subscribe message model. Thruway使用支持发布和订阅消息模型的WAMP。 You could use the AutobahnJS JavaScript library on the browser side to subscribe to events published by PHP when it makes database updates. 您可以使用浏览器端的AutobahnJS JavaScript库在更新数据库时订阅PHP发布的事件。

Disclaimer: I am a project maintainer for Thruway. 免责声明:我是Thruway的项目维护者。

The best way to do so is the use of realtime technologies such as nodejs, however there is a way around in php (with javascript/jquery). 最好的方法是使用实​​时技术,例如nodejs,但是php中有一种方法(使用javascript / jquery)。 I once develop a chat with php and javascript. 我曾经用php和javascript开发聊天功能。 All i did is set five seconds interval in javascript to listen to the server for any new message and append it to the chat box. 我所做的全部是在javascript中将间隔设置为五秒钟,以侦听服务器中是否有任何新消息并将其附加到聊天框。

如果您的Web服务器是节点,请使用websockets,否则,另一种方法是每30秒左右进行长时间轮询(使用setInterval)以查询数据库。

you can use this code: 您可以使用以下代码:

function checkUpdate()
{
 jQuery.ajax({
   type: "POST",
   url: "your.php",
   data: "name=currentUser&",   //our any other data you want to check
   success: function(msg){
     if(msg.indexOf('no Updates') !== -1 )
         {
            alert( "You have an update" );
     }
 });
}

You can use the above code to call and get response from your.php and will alert when the response doesnt contain "no Updates." 您可以使用上面的代码从your.php调用并获取响应,并在响应中不包含“无更新”时发出警报。 I suggest you to do this periodically by this code every 2 minute: 我建议您每2分钟通过以下代码定期执行此操作:

window.setInterval("checkUpdate()", 2*60*1000); // our any other period you want

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM