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

I am trying to use server sent event to get information from the database and update on my html page, immediately a new message enters, these are my codes

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>    

at the update.php,I have this

<?php
include 'first.php';

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

?>

At first.php, I have this

        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)."

";

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

        }

It worked well except that I expected it to update data in the divs in the html page immediately a new message comes in the messages_tb but it's not working like that, I have to refresh the page before I can get the new message in the div. Please, help out. thanks

</div>
duanqianhuan3994
duanqianhuan3994 非常感谢,非常感谢您的贡献。请帮助我解答我最初的问题
大约 2 年之前 回复
dongshiru5913
dongshiru5913 请阅读有关防止SQL注入的信息。
大约 2 年之前 回复

1个回答



我想在scope()上添加 $ scope。$ apply()</ code>。message handler应该适用于 你。</ p>

  source.onmessage = function(event)
{
$ scope.my_messages = JSON.parse(event.data);
$ scope。$ apply ();
}
</ code> </ pre>

原因是,angular可能不知道更新数据的普通java脚本。 如此有力地你可以告诉angular更新范围。</ p>
</ div>

展开原文

原文

I guess adding $scope.$apply() in on scope().message handler should work for you.

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

Reason is, angular might not be aware of plain java script updating the data. so forcefully you can tell angular to update the scope.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐