dozc1071 2018-09-16 00:50 采纳率: 100%
浏览 95
已采纳

使用服务器发送事件从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>
  • 写回答

1条回答 默认 最新

  • drgawfsf1069 2018-09-17 10:42
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!