我可以执行crud与SSE实时当用户添加一些东西到数据库或更新,以显示给所有连接的用户,我想知道,如果我可以做这件事使用php或我去与javascript,因为我想建立一个管理面板,管理员添加博客帖子,如果用户在博客上,以实时显示他们。谢谢!
var source = new EventSource("real.php");
source.onmessage = function(event) {
var jdata = JSON.parse(event.data);
console.log(jdata);
document.getElementById("result").innerHTML += jdata.firstName + "<br>";
};这是我的测试js,这是php:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$data = array(
'firstName'=>'Test',
'lastName'=>'Last'
);
$str = json_encode($data);
echo "data: {$str}\n\n";
flush();
?>现在这个例子只是一遍又一遍地添加到#result html中,我想要检测数据库中何时是新的东西,然后将新的东西实时添加到html中。
发布于 2020-07-13 07:12:59
好的,
为了让它工作,你需要一个事件日志来记录你想要跟踪的每个操作。为您要跟踪的每个操作向event_log添加行。
最小示例(虚构数据)-存储在表中(例如event_log):
[
'timestamp' => 1,
'table' => 'user'
'id' => '99',
'action' => 'create'
'data' => [...]
],[
'timestamp' => 1234,
'table' => 'posts',
...
]现在,每次调用real.php时,都会查询具有比上次检查更新的条目的event_log。为了做到这一点,你的php脚本应该是这样的:
<?php
// disable buffering to receive output immediately
ini_set('output_buffering','off');
header("Content-Type: text/event-stream");
$lastChecked = time(); // save current timestamp
while (true) // runs until connection gets terminated
{
// query event_log where time > $lastChecked
// echo accoring to link provided
// reset lastChecked
$lastChecked = time();
// wait 1 second before checking event_log again
sleep(1);
}https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Fields
SSE示例:https://github.com/mdn/dom-examples/blob/master/server-sent-events/sse.php
在通过onmessage接收到事件之后,您必须使用JS添加/编辑或删除DOM的元素,以使这些更改对用户可见。
您可能希望使用特定于事件的处理程序:https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Named_events
在JS中:
source.addEventListener('<your_event_name>', function(event) { /** event.data ... */ })https://stackoverflow.com/questions/62866507
复制相似问题