我需要 PHP 将输出流式传输到 Javascript 但 Javascript 保留旧响应并像这样打印它们......
控制台日志:
[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。
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;
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句