尝试创建一个小型通知系统。当用户填写个人资料时,他的验证状态在数据库中设置为1,然后我想显示一个通知,嘿,你现在已经验证了#34;。在互联网上搜索了很多,但没有任何东西能帮助我实现目标。如果数据库中的状态为1,我会在test.php
中获得事件:verification_ok,但如果为0,则获得Maximum execution time of 120 seconds exceeded
。另外,我的客户端代码中没有任何回复。
这是服务器端代码(test.php)。
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header("Connection: Keep-alive");
require_once $_SERVER['DOCUMENT_ROOT'].'/PHP/scripts/no_session_redirect.php';
$key = true;
$ver = $user_home->runQuery("SELECT verification_status FROM verification WHERE user_id=:user_id");
$ver->execute(array(":user_id"=>$user_id));
$status = $ver->fetch(PDO::FETCH_ASSOC);
while($key){
if($status["verification_status"] == 1){
pushNotification($status["verification_status"]);
$key = false;
}else{
$status["verification_status"];
sleep(10);
}
}
function pushNotification() {
echo "Event: verification_ok\n";
}
这是客户端代码:
$(document).ready(function() {
if (typeof(EventSource) !== "undefined") {
// Yes! Server-sent events support!
var source = new EventSource("test.php");
source.addEventListener("verification_ok", function(e) {
console.log(e.data);
}, false);
source.addEventListener("open", function(e) {
}, false);
source.addEventListener("error", function(e) {
if (e.readyState == EventSource.CLOSED) {
console.log("Error - connection was lost.");
}
}, false);
} else {
// Sorry! No server-sent events support..
}
});