我正在尝试将从文件读取的数据流式传输到 chrome 客户端。我能够成功传输数据,但我的响应被缓存了,我想防止这种情况发生。出现这种情况是因为我的平面文件包含彼此独立的数据条目,我想同样对待它们。例如,我的文件包含:
{idle_time:94125387364,system_time:98954710321,user_time:3683963615}
{idle_time:94125387789,system_time:98954710456,user_time:3683963845}
{idle_time:94125387876,system_time:98954710678,user_time:3683963986}
因此,我收到的不是 {idle_time:94125387876,system_time:98954710678,user_time:3683963986} (THIRD ENTRY) 作为 xmlhttprequest.responsetext
{idle_time:94125387364,system_time:98954710321,user_time:3683963615} <br/>
{idle_time:94125387789,system_time:98954710456,user_time:3683963845} <br/>
{idle_time:94125387876,system_time:98954710678,user_time:3683963986}
注意:我不担心断线标签和空格。
我的 PHP 脚本看起来像这样,test.php
<?php
set_time_limit(0);
$filename = 'D:\Smoke_Test\data.txt';
function flush2 (){
echo(str_repeat(' ',256));
// check that buffer is actually set before flushing
if (ob_get_length()){
@ob_flush();
@flush();
@ob_end_flush();
}
@ob_start();
}
$file_last_modified_time = 0;
while(true)
{
$modified_time = filemtime($filename);
$processor_info = "";
if ($file_last_modified_time < $modified_time)
{
header("Expires: Sun, 20 Jan 1985 00:00:00 GMT"); // date in the past
header("Cache-Control: no-cache");
header("Pragma: no-cache");
$file_last_modified_time = $modified_time;
$handle = fopen($filename,"r");
$processor_info = fgets ($handle);
fclose ($handle);
@ob_clean();
echo $processor_info."<br/>";
//flush2();
}
flush2();
sleep(1);
clearstatcache(true, $filename);
}
?>
我的 html 页面如下所示: Home.htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript" language = "javascript">
function read_file ()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 || xmlhttp.readyState==3 ) //&& xmlhttp.status==200)
{
handle_data (xmlhttp.responseText);
}
}
xmlhttp.open("POST","test.php",true);
xmlhttp.send();
}
function handle_data (input)
{
document.getElementById("txtResponse").innerHTML=input;
}
</script>
</head>
<body>
<p>
<input type="button" id="dtnSendRequest" value="Send Request" onclick="read_file()"/>
</p>
<p>
response : <span id="txtResponse"></span>
<!-- <input type="text" id="txtResponse" width="500"/> -->
</p>
</body>
</html>