服务器发送的事件监听器周期性地触发

时间:2016-07-17 21:27:51

标签: php server-sent-events

我正在根据此文档实现服务器发送的事件: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events 我正在执行脚本并注册事件监听器,如下所示:

      $("form").on("submit", function (event) {
          event.preventDefault();
          var data = { action: "add", username: $("#username").val(), einsatz: $("#inputEinsatz").val() };
          $.post("changeuser.php", data, function (data) {
              $("#result").text(data);

          });
      });
      var evtSource = new EventSource("changeuser.php");
      evtSource.onmessage = function(e) {
          $("#result").text(e.data);
      }

脚本changeuser.php:

error_reporting(E_ALL);
ini_set('display_errors', true);

$result = file_get_contents("users.json");
if ($result == FALSE) $users = array();
else $users = json_decode($result, true);
var_dump($result, $users);

/*$result = file_get_contents("status.json");
if ($result == FALSE) $status = array();
else $status = json_decode($result, true);*/

$error = FALSE;
$message = "";
$username = $_POST["username"];
$einsatz = $_POST["einsatz"];
$action = $_POST["action"];
switch ($action) {
case "add":
    if(array_key_exists ($username, $users)) {
        $error = TRUE;
        $message = "Benutzer " . $username . " existiert schon";
    } else {
        $newuser = array(
            "username" => $username,
            "einsatz" => $einsatz
        );
        $users[] = $newuser;
    }
    break;
}
$result = file_put_contents("users.json", json_encode($users));
$data = array(
    "action" => $action,
    "username" => $username,
    "error" => $error,
    "message" => $message,
    "users" => $users
);
header("Content-Type: text/event-stream\n\n");
echo("data: " . json_encode($data) . "\n\n");

我的问题是消息事件每2秒循环触发一次。如果我删除了header指令并检查$ .post的回调,一切正常。

0 个答案:

没有答案