繁体   English   中英

使用服务器发送的事件从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();

?>

首先,我有这个

        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页的divs中更新数据,但不能正常工作,我必须刷新页面,然后才能在div中获取新消息。 请帮帮忙。 谢谢

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

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

原因是,angular可能不知道纯Java脚本会更新数据。 因此您可以有力地告诉angular更新范围。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM