2017-03-16 34 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