当发生服务器端事件时,PHP更新页面

时间:2018-07-12 15:45:33

标签: php events server-sent-events fuelphp eventsource

当其他页面接收并保存一些数据而不重新加载页面时,我正在尝试更新页面。我想使用保存的数据,因此,如果可能的话,我想直接发送它,而不必调用数据库。实际数据将是一个键控数组。

我当前正在尝试使用服务器发送事件(SSE)发送更新网页,接收页面会立即保存数据。我当然愿意接受其他解决方案。

下面是一些在FuelPHP框架中编写的PHP测试代码,我正在努力尝试找出简化数据的问题。

<?php
class Controller_Test extends Controller_Rest
{
    public function get_receiverPage()
    {
        $data = input::get('test');
        //do some stuff
        if ($data['test'] == 'some circumstance')
        {
            /*
            send $data to Server Side Event handler
            or directly to display page if possible
            */
        }
        //continue with some other stuff
    }

    //this should send an update to /display
    public function action_ServerSideEventHandler()
    {
        // this is some modified code from a sample.

        //what headers should be used?
        header("Content-Type: text/event-stream");

        while (true)//should this be (isset($test))?
        {
            echo "data: ".$test."\n\n";
            unset($test);

            // no idea what to do with flush(), sleep, and related stuff
            // the following is purely based off the sample

            // flush the output buffer and send echoed messages to the browser
            while (ob_get_level() > 0) {
                ob_end_flush();
            }
            flush();
            // break the loop if the client aborted the connection (closed the page)

            if ( connection_aborted() ) break;
            // sleep for 1 second before running the loop again

            sleep(1);
        }
    }

}
?>

这是显示侧代码的基本功能。实际上,我将使用数据来创建表行。

<script>


$(document).ready(function(){
if(typeof(EventSource) !== "undefined") {
        var source = new EventSource("/test/ServerSideEventHandler"); // /test/1 /receiverAPI/list
            source.addEventListener('message', function(e) {
              console.log(e.data);
            }, false);
    } else {
        alert("Your browser does not support server-sent events. Please use any modern browser other than internet explorer/microsoft edge.");
    }
});
</script>

0 个答案:

没有答案