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

问题描述 投票:0回答:1

我正在尝试使用服务器发送事件从数据库中获取信息并在我的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中获取新消息。请帮忙。谢谢

javascript php mysql angularjs server-sent-events
1个回答
0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.