【问题标题】:IFrame Comet response contains no dataIFrame Comet 响应不包含数据
【发布时间】:2010-07-26 09:41:51
【问题描述】:

我正在试验 Comet,但我坚持通过隐藏的 IFrame(“永久帧”)来实现它。

这是我的 index.html:

<!DOCTYPE HTML>
<html>
  <head>
    <script type="text/javascript">
    cometResponse = function() {
        var debugOut = document.getElementById('debugOutput');
        return function(response) {
            debugOut.innerHTML = response.number; 
        }
    }
    </script>
  </head>
  <body>
    <div id="debugOutput"></div>
    <iframe src="comet.php"></iframe>
  </body>
</html>

这是 comet.php 文件:

<?php
set_time_limit(0);
header('Content-Type: text/html');
header('Cache-Control: no-cache, must-revalidate'); 
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Transfer-Encoding: chunked');
flush();
ob_flush();

$response = '<script type="text/javascript">
parent.cometResponse({
    number: %1$d
});
</script>';

for ($i = 0; $i < 2; $i++) {
    sleep(1);
    $data = sprintf($response, $i);
    $output = strtoupper(dechex(strlen($data)))."\r\n".$data."\r\n";
    echo $output;
    flush();
    ob_flush();
}
echo "0\r\n\r\n";

加载页面后,浏览器似乎在“等待”响应。几秒钟后,Firebug 显示一个带有这些响应标头的空响应:

HTTP/1.1 200 OK
Date: Mon, 26 Jul 2010 09:34:04 GMT
Server: Apache/2.2.14 (Win32) PHP/5.2.12
X-Powered-By: PHP/5.2.12
Cache-Control: no-cache, must-revalidate
Expires: Mon, 26 Jul 1997 05:00:00 GMT
Transfer-Encoding: chunked
Vary: Accept-Encoding
Content-Encoding: gzip
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: text/html;charset=ISO-8859-2

由于响应被视为空,因此应该在响应中的标记也不会被执行。

但是,如果我删除“Transfer-Encoding: chunked”标头,内容会正确发送到浏览器,但在脚本末尾全部是一大块,正如预期的那样。

我只是找不到这里出了什么问题。

【问题讨论】:

  • 对此有何改进?

标签: php javascript http iframe comet


【解决方案1】:

两种猜测:

  1. 内容编码:gzip

    也许 mod_gzip 不能正常工作? 您是否尝试过其他主机?

  2. 也许 Firefox 会忽略代码,如果 它不在

【讨论】:

  • 1.也许,我会调查一下。 2. 不,Firebug 通常会显示响应的原始内容。
【解决方案2】:

这可能对其他人有帮助,这是我的解决方法:

<?php
header('Content-Encoding: chunked');
header('Transfer-Encoding: chunked');
header('Content-Type: text/html');
header('Connection: keep-alive');
header('Cache-Control: no-cache, must-revalidate');
flush();
set_time_limit(0);
function chunk($data) {
    echo sprintf("%x\r\n%s\r\n", strlen($data), $data);
    flush();
    ob_flush();
}
// Code to output data here.
// The following loop is an example.
for($i = 0; $i < 5; $i++) {
    chunk('<script type="text/javascript">window.top.test();</script>');
    sleep(1);
}
chunk('');
?>

它需要在输出末尾有一个空块。

然后你可以像这样调用函数chunk来简单地输出数据:

chunk('data');

【讨论】:

    猜你喜欢
    • 2015-07-19
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 2022-01-15
    • 2012-08-26
    • 2012-04-03
    相关资源
    最近更新 更多