SSE - Codeigniter - 输出内容 [英] SSE - Codeigniter - Output content

查看:36
本文介绍了SSE - Codeigniter - 输出内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 PHP Codeigniter 应用程序中实现服务器发送的事件.

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

我有一个长时间运行的脚本,SSE 会为用户显示进度条.

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

这一点很好用.

缺失的部分:当所有数据都准备好后,我如何显示我的 HTML 内容?

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();
}

推荐答案

您有两个选择:您可以将新视图的所有 html 发送到 SSE 连接,然后断开前端连接.

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

但更简单的方法是让 JS 代码检测进度表何时达到 100%,然后:

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

  1. 断开 SSE 连接
  2. 请求一个新的 URL,它将获取并显示您所创建的新视图想送.

即进度表使用SSE,正常显示使用正常请求.

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

这篇关于SSE - Codeigniter - 输出内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆