Perl CGI 在 If-Else / While 期间不更新会话变量

Perl CGI does not update session variables during If-Else / While

下面的代码有一个 AJAX 调用,它启动一个 if 语句并从最后存储的会话参数 + 10 开始计数。

另一个 AJAX 调用立即开始轮询 form.cgi 当前会话参数。

我希望会话参数根据时间条件每秒更新一次,因此我应该一次获得一个递增的数字流。 (轮询代码也以一秒为增量 运行)。

这是我对 Web 浏览器控制台的期望,每隔一秒:

1,2,3,4,5,6,7,8,9,10,11...(press submit again)...12,13,14,15...etc..

问题是轮询 AJAX 调用返回的值每个 while 循环仅更新一次(每十秒)

1,1,1,1,1,1,1,1,1,1,10,10, (press submit again)...10,10,10,10,10...

似乎会话变量仅在 If 和 While 完成时才提交到服务器存储。

有办法解决这个问题吗?我计划 运行 许多带有 If 语句的系统脚本,并希望能够轮询 form.cgi 更新,而不必等到所有操作都完成。

form.cgi

#!/usr/bin/perl

use strict;
use warnings;

use CGI;
use CGI::Carp 'fatalsToBrowser'; # sends error messages to the browser!
use CGI::Session;
use JSON;

my $workTimer = 1; # In milliseconds.

my $query = CGI->new();
my $session = CGI::Session->new($query);
print $session->header();

if(defined $query->param('name')){

    my $sec = time();
    my $count = $session->param('script1');
    my $max = $count + 10;

    while($count < $max){
        if(time() > $sec + $workTimer){
            $count = $session->param('script1');
            $count = $count + 1;
            $session->param('script1', $count);
            $sec = time();
        }
    }

    print "While finished.";
}
elsif(defined $query->param('polling')){
    my @pollingArray = ();

    push(@pollingArray, $session->param('script1'));

    my $json->{"poll-reply"} = \@pollingArray;
    my $json_text = to_json($json);

    print "$json_text";
}
else{
    print <<"EOF";
<html><head>
        <script src="jquery-2.2.0.min.js" defer></script>
        <script src="app.js" defer></script>
</head><body>
EOF

    # Print the form area.
    print <<"EOF";
    <form id="test-form">
        <input type="submit" name="submit" id="submit"/>
    </form>
EOF

    # Print the bottom of the HTML page.
    print <<"EOF";
    </body>
</html>
EOF

}

app.js

$('#submit').on("click", function(e){
    e.preventDefault();
    $.ajax({
        url: "/form/form.cgi",
        type: "post",
        data: {
            name: "-"
        },
        success: function(data){
            console.log(data);
        }
    });
    var polling = pollingForStatus();
});

function pollingForStatus(){
    return window.setInterval(function(){ 
        $.ajax({
            url: "/form/form.cgi",
            type: "post",
            data: {
                polling: "poll"
            },
            success: function(data){
                console.log(data);
            }
        }); 
    }, 1000);
}

在对您希望在当前请求之外可见的会话进行更新后尝试调用 flush()。

https://metacpan.org/pod/CGI::Session#flush