SSE - Codeigniter - Output content

梦想与她 提交于 2019-12-11 09:47:10

问题


I am implementing Server-Sent Events in my PHP Codeigniter application.

I have a long running script and SSE shows progress bar for the user.

This bit works great.

The missing piece: how do I display my HTML content when all the data is ready?

PHP:

public function LongRunningScript() {
    header("Content-Type: text/event-stream");
    header("Cache-Control: no-cache");
    header("Connection: keep-alive");

    function send_message($id, $progress) {
        $d = array('message' => "", 'progress' => $progress);
        echo "id: $id" . PHP_EOL;
        echo "data: " . json_encode($d) . PHP_EOL;
        echo PHP_EOL;
        ob_flush();
        flush();
    }

    //LONG RUNNING TASK
    for ($i = 1; $i <= 10; $i++) {
        send_message($i, $i * 10);
        sleep(1);
    }

    // now all data is ready and i would like to do something like this:
    // $this->data['content'] = $this->load->view('view.php', $this->data, true);
}    

JS:

function startTask() {
    event_source = new EventSource('controller/LongRunningScript');

    //a message is received
    event_source.addEventListener('message', function (e) {
        var result = JSON.parse(e.data);

        if (e.lastEventId == 'CLOSE') {
            //addLog('Received CLOSE closing');
            event_source.close();
            var pBar = document.getElementById('progressor');
            pBar.value = pBar.max; //max out the progress bar
        } else {
            var pBar = document.getElementById('progressor');
            pBar.value = result.progress;
            var perc = document.getElementById('percentage');
            perc.innerHTML = result.progress + "%";
            //perc.style.width = (Math.floor(pBar.clientWidth * (result.progress / 100)) + 15) + 'px';
        }
    });

    event_source.addEventListener('error', function (e) {
        event_source.close();
    });
}

function stopTask() {
    event_source.close();
}

回答1:


You have two options: you could send all the html for the new view down the SSE connection, then have the front-end disconnect.

But simpler would be to have the JS code detect when the progress meter has reached 100%, and then:

  1. Disconnect the SSE connection
  2. Request a new URL, which would fetch and display that new view that you want to send.

I.e. use SSE for the progress meter, use a normal request for the normal display.



来源:https://stackoverflow.com/questions/44495797/sse-codeigniter-output-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!