dongqiu9018 2017-06-12 09:21
浏览 80

SSE - Codeigniter - 输出内容

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条回答

  • douzuizhuo0587 2018-03-30 08:21
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题