使用服务器发送事件从 php 中的 mysql 获取数组

Using server sent event to get an array from mysql in php

我正在尝试使用服务器发送的事件从数据库中获取信息并在我的 html 页面上更新,立即有一条新消息进入,这些是我的代码

function update()
    {  
      if(typeof(EventSource)  !="undefined")
      {  
        var source=new EventSource("update.php");
        
       
        source.onmessage=function(event)
        {
          $scope.my_messages=JSON.parse(event.data)
        }
      }
    }
update();
<div ng-repeat="x in my_messages">
        <div>{{x.sender_username}}</div>
        <div>{{x.title}}</div>
        <p>{{x.messages}}</p>
 </div>    

在update.php,我有这个

<?php
include 'first.php';

$newUser= new Participant();
    $newUser->connect();
    $newUser->call_new_message();

?>

在first.php,我有这个

        public function call_new_message()
        {
        $sender=$_SESSION['username'];
        $receiver=$_SESSION['receiverUsername'];
            $a = mysqli_query($this->con, "SELECT * from messages_tb WHERE sender_username= '$sender' and receiver_username='$receiver' ");
                 if ($a) {
                $s=$a->fetch_all(MYSQLI_ASSOC);
                header('Content-Type: text/event-stream');

 header('Cache-Control: no-cache');

 echo"data:".json_encode($s)."\n\n";

 flush();
            // echo json_encode($s);
            }
            else{
                echo "An error occurred";
            }

        }

它运行良好,只是我希望它能立即更新 html 页面中 div 中的数据,messages_tb 中会立即收到一条新消息,但它不是那样工作的,我必须刷新页面才能在 div 中获取新消息。请帮忙谢谢

我想在 scope() 中添加 $scope.$apply()。消息处理程序应该适合你。

source.onmessage=function(event)
    {
      $scope.my_messages=JSON.parse(event.data);
      $scope.$apply();
    }

原因是,angular 可能不知道普通 java 脚本更新数据。如此有力,您可以告诉 angular 更新范围。