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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵