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 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)