簡體   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