繁体   English   中英

javascript EventSource更新php文件中的导入进度

[英]javascript EventSource to update import progress in a php-file

我正在尝试实现一个进度条,用于将记录导入数据库。

导入是使用jQuery的$ .post(...)发送到服务器上的php脚本开始的。

我尝试了几种方法:

  • 开始导入并将进度写入SESSION-Var,并通过EventSource进行第二次调用来轮询var

用于导入的php类似于:

foreach($importProduct as $ip){
    $_SESSION['importedProducts'] += 1;
    // ... do the import-stuff
}

然后使用EventSource获取导入进度

var jsonStream = new EventSource('eventSource.php');

    if(typeof(EventSource) === "undefined"){
        alert('browser doesn\'t support EventSource');
    }else{
        console.log('fetching stream');
        jsonStream.onmessage = function (e) {
            console.log('stream: ' + e.data);
            $('#eventReturn').html(e.data);
           //var message = JSON.parse(e.data);
          // handle message
        };
    }

并在PHP脚本中

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

while(1){

    echo 'data: {"imported":"'.$_SESSION['importedProducts'].'","total":"'.$_SESSION['totalProductsToImport'].'"}';
    echo "\n\n";
    ob_flush();
    flush();
    sleep(1);
}

这显然不起作用,因为在两次调用之间未更新SESSION。

将进度写入文件,然后每秒读取一次,这似乎有点开销。

我尝试的另一件事是使用每秒调用一次的js函数,并尝试从同一脚本获取进度-但它会挂起,直到import-script完成

function uploadProgress(){

    // Fetch the latest data

    $.get('progress.php', function(data){
        console.log(data);
    });

    setTimeout(uploadProgress, 5000);
}

有任何想法吗?

注意:我将在每次通话(session_start)时启动会话。 我知道«while(1)»会创建一个无限循环... :)

我找到了解决方案。

诀窍是在两次呼叫之间打开和关闭会话。

因此,在导入脚本中:

foreach($importProduct as $ip){
    session_start();
    $_SESSION['importedProducts'] += 1;
    session_write_close();
    // ... do the import-stuff
}

在进度脚本中:

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

while(1){
    session_start();
    echo 'data: {"imported":"'.$_SESSION['importedProducts'].'","total":"'.$_SESSION['totalProductsToImport'].'"}';
    echo "\n\n";
    ob_flush();
    flush();
    session_write_close();
    sleep(1);
}

现在,会话会不断更新,我可以使用EventSource方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM