duanshan1856 2014-11-01 01:48
浏览 52
已采纳

XMLHttpRequest readyState HEADERS_RECEIVED等待整个文件下载

According to MDN, the XMLHttpRequest readyState event fires 5 events, listed below.

0    UNSENT              open()has not been called yet.
1    OPENED              send()has not been called yet.
2    HEADERS_RECEIVED    send() has been called, and headers and status are available.
3    LOADING             Downloading; responseText holds partial data.
4    DONE                The operation is complete.

This would seem to suggest that the HEADERS_RECEIVED would be available before the entire file has downloaded, especially during a long transfer. However, in my testing, while the events do fire in this order, both HEADERS_RECEIVED and LOADING fire at virtually the same time as the DONE event.

Here is a basic example that illustrates my issue. The OPENED event fires immediately, but HEADERS_RECEIVED, LOADING, and DONE all wait 5 seconds. I ran this test with PHP 5.5 on a local Apache 2.4 server in both Firefox and Chrome.

JavaScript:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
    console.log("readyState:", xmlhttp.readyState);
};
xmlhttp.open("GET", "handler.php", true);
xmlhttp.send();

handler.php:

<?php
header( 'Content-Type: text/plain' );
echo "start
";
sleep( 5 );
echo "end
";

It seems the only way to get the headers before the content is to first make a HEAD request, then a full request. Is this expected behavior or am I missing something?

UPDATE:

Using a 1GB file symlinked over a slow network share, or a PHP file that outputs a substantial amount of output (example below) does fire the HEADERS_RECEIVED sooner. This seems to be somewhat unreliable though. I've tried using PHP's flush function before sleep, but it doesn't help.

<?php
header( 'Content-Type: text/plain' );
echo "start
";
$i = 10000000;
while( $i-- ){
    echo "1
";
}
echo "end
";

Is there a way to reliable send headers without waiting for the content to send?

  • 写回答

1条回答 默认 最新

  • dthok9648 2014-11-01 02:07
    关注

    At least in the case of your example, I'm guessing PHP isn't actually flushing the buffer (and thus sending the headers) until after the sleep, but I'm not sure if that would explain this behavior if you've encountered it using actual file downloads.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog