2017-03-16 33 views
0

我需要PHP流输出到Javascript支持,但是使用Javascript保留旧回应并打印它们是这样的...如何正确刷新PHP输出缓冲区?

控制台日志:

[0]: Line to show. 
[0]: Line to show.[1]: Line to show. 
[0]: Line to show.[1]: Line to show.[2]: Line to show. 
[0]: Line to show.[1]: Line to show.[2]: Line to show.[3]: Line to show. 
[0]: Line to show.[1]: Line to show.[2]: Line to show.[3]: Line to show.[4]: Line to show. 

[0]: Line to show.[1]: Line to show.[2]: Line to show.[3]: Line to show.[4]: Line to show.Array 
(
    [0] => [0]: Line to show. 
    [1] => 
    [2] => 
    [3] => [1]: Line to show. 
    [4] => 
    [5] => 
    [6] => [2]: Line to show. 
    [7] => 
    [8] => 
    [9] => [3]: Line to show. 
    [10] => 
    [11] => 
    [12] => [4]: Line to show. 
    [13] => 
    [14] => 
) 

所以使用Javascript控制台日志状态的responseText的是“节能”旧的回应。然而,看看我保存在PHP中的数组,你可以看到没有以前的回声被刷新到JS。

的Javascript:

   $.ajax({ 
        url: "../controller/controller.php", 
        type: "POST", 
        data: {operation: 'rxMode'}, 
        xhr: function(){ 
         var xhr = $.ajaxSettings.xhr(); 
         xhr.onprogress = function(e){ console.log(e.currentTarget.responseText); }; 
         console.log(xhr); 
         return xhr; 
        } 
       }); 

PHP:

 $out = array(); 
     for ($i = 0; $i<5; $i++){ 
      echo "[$i]: Line to show."; 
      array_push($out, ob_get_contents()); 
      ob_flush(); 
      array_push($out, ob_get_contents()); 
      flush(); 
      array_push($out, ob_get_contents()); 
      sleep(2); 
     } 
     print_r($out); 

我的期望responseText的是

[0]: Line to show. 
[1]: Line to show. 
[2]: Line to show. 
[3]: Line to show. 
[4]: Line to show. 

编辑:我不想删除旧的答复,而我宁愿使用Javascript只给我我想要的responseText。

+0

移除PHP数组和print_r并不能解决问题,它仅用于调试。 –

+0

也许尝试在下一个响应之前清除xhr var?与'remove'命令一样。 **但是**您将不得不从xhr声明中移除'var'。 – Soaku

+0

不清楚你的意思是通过删除变量。它在jQuery ajax包装中,所以删除它会导致ajax指向错误的变量? –

回答

2

responseText始终包含来自服务器的整个响应。当您使用progress事件时,它包含到目前为止累积的响应,而不仅仅是从服务器最近刷新时添加到响应中的增量字符串。

将前一个响应文本的长度保存在变量中,然后在随后的调用中仅打印子字符串。

var responseLen = 0; 
$.ajax({ 
    url: "../controller/controller.php", 
    type: "POST", 
    data: {operation: 'rxMode'}, 
    xhr: function(){ 
     var xhr = $.ajaxSettings.xhr(); 
     xhr.onprogress = function(e){ 
      console.log(e.currentTarget.responseText.substr(responseLen)); 
      responseLen = e.currentTarget.responseText.length; 
     }; 
     console.log(xhr); 
     return xhr; 
    } 
}); 
+0

感谢您的解决方案,但我希望得到解决问题的根源而不是症状的答案。在PHP和我的Apache服务器之间的某些时候,某些东西可以保存旧的响应,并将其刷新到Javascript。谢天谢地,JS中的变量没有限制,但如果我让这台服务器运行了几天,并且它保持在无限循环中串流这个字符串响应,它会很快变大... –

+0

这是浏览器保存它。 'responseText'是到目前为止收到的全部响应,而不仅仅是PHP中最近刷新的位。 – Barmar

+0

这听起来像你应该使用像WebSockets而不是XHR。 – Barmar