-1

假设我有一个虚拟服务器端代码(ajax_response.php),如下所示:

<?php

for ($i = 1; $i <= 10; $i++) {
    echo $i;
    sleep(1);
}

?>

这意味着 10 秒后它将回显“12345678910”。

我也有以下 jquery 代码:

$.ajax({
        type: 'POST',
        url: 'ajax_response.php'
    }).then(function(results) { 
        //... success

    }, function {
        //... execute if error occurs
} );

我可以使用上面的 ajax 从 ajax_response.php 获取响应,但问题是,只有在 ajax_response.php 完成执行(需要 10 秒)时才会调用成功函数(即 .then 中的第一个函数)。

我想知道我是否可以提高效率。IE。在 php 文件中调用 echo 后,我会立即从客户端获得响应。

如果您可以包含一些示例代码,那就太好了。

4

1 回答 1

0

在javascript方面

   var interval;
   $.ajax({
        beforeSend: function(){
            interval = setInterval(function(){
                    $.get("http://example.com/pr.txt").done(function(progress){
                        console.log(progress)
                    })
                },10);
        },
        type: "POST",
        url: "http://example.com/req.php",
        data: reqdata,
        cache: false,
        success: function(html) {
            clearInterval(interval);
            var values = html.split('[mydata]');
            var mydata = values[1];
        }
   });

`

在 PHP 端

unlink("progress.txt");
while ($i <= 20) {
    writeToFile(progress, "Mail sent to $i <br>");
    sleep(4);
    $i++;
}
$final = array('status'=>'ok', 'numbers'=>$success_numbers);
echo json_encode($final);

`

于 2018-03-05T19:36:56.323 回答