我需要PHP将输出流式传输到Javascript,但是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;
}
});
因此,Javascript控制台记录了responseText“保存”旧响应的状态。但是,看看我在PHP中保存的数组,你可以看到没有以前的回声被刷新到JS。
使用Javascript:
$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);
PHP:
[0]: Line to show.
[1]: Line to show.
[2]: Line to show.
[3]: Line to show.
[4]: Line to show.
我想要的responseText是
<form name="contactform" method="post" action="send_form_email.php">
<table width="450px">
<tr>
<td valign="top">
<label for="first_name">First Name *</label>
</td>
<td valign="top">
<input type="text" name="first_name" maxlength="50" size="30">
</td>
</tr>
<tr>
<td valign="top"">
<label for="last_name">Last Name *</label>
</td>
<td valign="top">
<input type="text" name="last_name" maxlength="50" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="email">Email Address *</label>
</td>
<td valign="top">
<input type="text" name="email" maxlength="80" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="telephone">Telephone Number</label>
</td>
<td valign="top">
<input type="text" name="telephone" maxlength="30" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="comments">Comments *</label>
</td>
<td valign="top">
<textarea name="comments" maxlength="1000" cols="25" rows="6"></textarea>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<input type="submit" value="Submit"> <a href="http://www.freecontactform.com/email_form.php">Email Form</a>
</td>
</tr>
</table>
</form>
编辑:我不想删除旧的回复,而是希望Javascript只给我想要的responseText。
答案 0 :(得分: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;
}
});