在perl CGI中分割AJAX响应?

时间:2010-07-28 00:59:21

标签: javascript ajax perl cgi

perl cgi脚本是否有可能将其AJAX响应分段为多个单独的HTTP响应?

说我有这段代码:

xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        onDataReceived(xmlhttp.responseText);
    }
    else if(xmlhttp.status!=200 && xmlhttp.status!=0) {    }
}
xmlhttp.open("POST","script.cgi",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(toURLString(options));

作为javascript(不要告诉我有关xml对象兼容性问题,即我知道,并不在意)。

和此:

print "Content-type: text/html\n\n";

my %form = Vars();
if($ENV{REQUEST_METHOD} eq "POST" )
{
    $|=1;
    for(my $i, (1..100000000))
    {
        print "1\n";
    }
}

如perl cgi。是否有可能在1s的多个单独数据包中打印出这个结果,而不是在最终输出之前生成100000000 1s?

1 个答案:

答案 0 :(得分:1)

请参阅此SO问题以了解可能的方法,但不是Perl特定的:

Dealing with incremental server response in AJAX (in JavaScript)

从链接的Wiki文章中,此链接似乎最相关:http://en.wikipedia.org/wiki/Comet_%28programming%29#XMLHttpRequest

但是,我强烈建议您考虑使用轮询方法而不是正在考虑的“服务器推送”

服务器将数据块存储为可访问文件(带有一些排序元信息)

print "Location: xxxx"; 
# Sorry, forgot the exact form of Location HTTP response.
# Location points to URL mapped to /home/htdocs/webdocs/tmp/chunk_0.html
my %form = Vars();
if($ENV{REQUEST_METHOD} eq "POST" )
{
    $|=1;
    $file_num = 0;
    my $fh;
    for(my $i, (1..100000000))
    {
        if ($i % 1000 == 0) {
            close $fh if $fh;
            open $fh, ">", "/home/htdocs/webdocs/tmp/chunk_${file_num}.html";
            # Add the usual error handling on open/close i'm too lazy to type
            $file_num++;
        }
        print $fh "1\n";
    }
    print $fh "\n##############END_TRANSMISSION__LAST_FILE####################\n";
    # This was a singularly dumb way of marking EOF but you get the drift
    close $fh;
}

AJAX轮询器逐个循环检索它们,处理包含下一个块的响应并查找元信息以了解下一个要轮询的内容(以及是否)。