如何向网络浏览器发送加载页面,然后在一段时间后发送结果页面

发布于 2024-08-27 18:20:48 字数 2113 浏览 4 评论 0原文

我已经浪费了公司至少半天的时间在互联网上搜索答案,而我却被困在了这里。我无法弄清楚所有不同技术选择(长轮询、ajax 流、comet、XMPP 等)之间的区别,并且我无法在我的 PC 上运行简单的 hello world 示例。

我正在运行 Apache 2.2 和 ActivePerl 5.10.0。 JavaScript 对于这个解决方案来说是完全可以接受的。我想做的就是编写一个简单的 Perl CGI 脚本,当访问该脚本时,它会立即返回一些 HTML,告诉用户等待或者可能发送一个动画 GIF。然后,在没有任何用户干预(没有鼠标点击或任何其他操作)的情况下,我希望 CGI 脚本在稍后的某个时间用查询的实际结果替换等待消息或动画 GIF。

我知道这是简单的事情,网站总是使用 JavaScript 来完成它,但我找不到一个可以在 Perl 中工作的可以剪切并粘贴到我的机器上的工作示例。

这是我从各种互联网资源编译的简单的 Hello World 示例,但它似乎不起作用。当我在 Web 浏览器中刷新此 Perl CGI 脚本时,它在 5 秒内不打印任何内容,然后打印“请耐心等待”网页,但不打印结果网页。所以 Ajax XMLHttpRequest 的东西显然不能正常工作。我做错了什么?

#!C:\Perl\bin\perl.exe

use CGI; 
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/; 

sub Create_HTML {
    my $html = <<EOHTML;
<html>
<head>
  <meta http-equiv="pragma" content="no-cache" />
  <meta http-equiv="expires" content="-1" />
  <script type="text/javascript" >

var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
 try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
  }
 }
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
    try {
        xmlhttp = new XMLHttpRequest();
    } catch (e) {
        xmlhttp=false;
    }
}
if (!xmlhttp && window.createRequest) {
    try {
        xmlhttp = window.createRequest();
    } catch (e) {
        xmlhttp=false;
    }
}

  </script>

  <title>Ajax Streaming Connection Demo</title>
</head>
<body>

  Some header text.
  <p>
  <div id="response">PLEASE BE PATIENT</div>
  <p>
  Some footer text.

</body>
</html>

EOHTML
    return $html;
  }

my $cgi = new CGI;
print $cgi->header;
print Create_HTML();

sleep(5);
print "<script type=\"text/javascript\">\n";
print "\$('response').innerHTML = 'Here are your results!';\n";
print "</script>\n";

I've wasted at least a half day of my company's time searching the Internet for an answer and I'm getting wrapped around the axle here. I can't figure out the difference between all the different technology choices (long polling, ajax streaming, comet, XMPP, etc.) and I can't get a simple hello world example working on my PC.

I am running Apache 2.2 and ActivePerl 5.10.0. JavaScript is completely acceptable for this solution. All I want to do is write a simple Perl CGI script that when accessed, it immediately returns some HTML that tells the user to wait or maybe sends an animated GIF. Then without any user intervention (no mouse clicks or anything) I want the CGI script to at some time later replace the wait message or the animated GIF with the actual results from their query.

I know this is simple stuff and websites do it all the time using JavaScript, but I can't find a single working example that I can cut and paste onto my machine that will work in Perl.

Here is my simple Hello World example that I've compiled from various Internet sources, but it doesn't seem to work. When I refresh this Perl CGI script in my web browser it prints nothing for 5 seconds, then it prints the PLEASE BE PATIENT web page, but not the results web page. So the Ajax XMLHttpRequest stuff obviously isn't working right. What am I doing wrong?

#!C:\Perl\bin\perl.exe

use CGI; 
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/; 

sub Create_HTML {
    my $html = <<EOHTML;
<html>
<head>
  <meta http-equiv="pragma" content="no-cache" />
  <meta http-equiv="expires" content="-1" />
  <script type="text/javascript" >

var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
 try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
  }
 }
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
    try {
        xmlhttp = new XMLHttpRequest();
    } catch (e) {
        xmlhttp=false;
    }
}
if (!xmlhttp && window.createRequest) {
    try {
        xmlhttp = window.createRequest();
    } catch (e) {
        xmlhttp=false;
    }
}

  </script>

  <title>Ajax Streaming Connection Demo</title>
</head>
<body>

  Some header text.
  <p>
  <div id="response">PLEASE BE PATIENT</div>
  <p>
  Some footer text.

</body>
</html>

EOHTML
    return $html;
  }

my $cgi = new CGI;
print $cgi->header;
print Create_HTML();

sleep(5);
print "<script type=\"text/javascript\">\n";
print "\$('response').innerHTML = 'Here are your results!';\n";
print "</script>\n";

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

烟雨扶苏 2024-09-03 18:20:48

如果您的流程依赖于查询字符串参数,则简单的元刷新就足够了。例如,如果他们加载http://yoursite.com/message?foo=1,那么就可以输出一个元标记,例如:

<meta http-equiv="refresh" content="0; http://yoursite.com/realquery?foo=1" />

以及一些包含“请稍候”消息的 HTML。 realquery 脚本实际上会执行查询,message 的 HTML 输出将保留在屏幕上,直到 realquery 提供一些输出。

如果查询依赖于 POST 数据,那么它会变得有点复杂,因为您无法重定向 POST。但是,您可以输出包含一些隐藏字段的表单并使用 Javascript 提交它。例如:

<script type="text/javascript">
    window.onload = function() { 
        document.getElementById( 'form_with_hidden_fields' ).submit();
    }
</script>

<form method="POST" action="realquery" id="form_with_hidden_fields">
    <input type="hidden" name="foo" value="1" />
    ...
</form>

Please wait while your query is processed...

如果您对 AJAX 解决方案感兴趣,这里有一个使用 jQuery 的示例:

$( '#submit-button' ).click( function() { 
    // show a "please wait" image
    $( '#status-div' ).html( '<img src="please_wait.gif" />' );  // animated gif

    // get form values
    var formdata = { foo: $( 'input#foo' ).val(),
                     ...
                   };

    // submit form via ajax:
    $.ajax( { type: "POST", url: "/realquery", data: formdata, success: function() { 
        $( '#status-div' ).html( '<img src="success.gif" />' );
    } );
} );

您可以将其附加到如下表单:

<form>
    <input type="text" name="foo" id="foo" />
    <input type="submit" id="submit-button" />
    <div id="status-div"> </div>
</form>

空的 status-div div 将接收一个指向的图像标签“请稍等”图像(可以是 gif 动画)。当 Ajax 查询完成时,它会被“成功”图像替换。

If your process relies on query-string parameters, a simple meta-refresh would suffice. E.g. if they load http://yoursite.com/message?foo=1, then that can output a meta tag like:

<meta http-equiv="refresh" content="0; http://yoursite.com/realquery?foo=1" />

And some HTML that has your "please wait" message. The realquery script would actually execute the query and the HTML output by message will remain on the screen until realquery provides some output.

If the query relies on POST data, then it gets a little more complicated, because you can't redirect a POST. You can, however, output a form with some hidden fields and use Javascript to submit it. For example:

<script type="text/javascript">
    window.onload = function() { 
        document.getElementById( 'form_with_hidden_fields' ).submit();
    }
</script>

<form method="POST" action="realquery" id="form_with_hidden_fields">
    <input type="hidden" name="foo" value="1" />
    ...
</form>

Please wait while your query is processed...

If you're interested in an AJAX solution, here's an example using jQuery:

$( '#submit-button' ).click( function() { 
    // show a "please wait" image
    $( '#status-div' ).html( '<img src="please_wait.gif" />' );  // animated gif

    // get form values
    var formdata = { foo: $( 'input#foo' ).val(),
                     ...
                   };

    // submit form via ajax:
    $.ajax( { type: "POST", url: "/realquery", data: formdata, success: function() { 
        $( '#status-div' ).html( '<img src="success.gif" />' );
    } );
} );

And you could attach that to a form like:

<form>
    <input type="text" name="foo" id="foo" />
    <input type="submit" id="submit-button" />
    <div id="status-div"> </div>
</form>

The empty status-div div will receive an image tag that points to a "please wait" image (this can be an animated gif). When the Ajax query finishes, it's replaced by a "success" image.

锦爱 2024-09-03 18:20:48

请参阅 Randal Schwartz 的通过 CGI 观看长进程

See Watching long processes through CGI by Randal Schwartz.

咋地 2024-09-03 18:20:48

这是使用 Friedo 的 HTTP 元刷新解决方案的完整工作示例。这不是我个人的首选解决方案,因为它会修改浏览器中的 URL,并且还会刷新整个网页。

#!C:\Perl\bin\perl.exe
use CGI; 
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/; 
sub html_page {
    my ( $meta_string, $results_string ) = @_;
    my $html = <<EOHTML;
<html>
<head>
  $meta_string
  <title>Two Stage Web Page Demo</title>
</head>
<body>
  Some header text.
  <p>
  $results_string
  <p>
  Some footer text.
</body>
</html>
EOHTML
    return $html;
  }

my $cgi = new CGI;
print $cgi->header;
if ($cgi->param()) {
    if ($cgi->param('doResults') eq "true") {
        sleep(5);
        print html_page('', 'Here are your results!');
    }
}
else {
    my $meta_refresh = '<meta http-equiv="refresh" content="0; /cgi-bin/twoStageScript.pl?doResults=true" />';
    print html_page($meta_refresh, 'PLEASE BE PATIENT');
}
exit;

Here is a complete working example using friedo's HTTP meta refresh solution. This is not my personal first choice solution because it modifies the URL in the browser and it also refreshes the whole web page.

#!C:\Perl\bin\perl.exe
use CGI; 
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/; 
sub html_page {
    my ( $meta_string, $results_string ) = @_;
    my $html = <<EOHTML;
<html>
<head>
  $meta_string
  <title>Two Stage Web Page Demo</title>
</head>
<body>
  Some header text.
  <p>
  $results_string
  <p>
  Some footer text.
</body>
</html>
EOHTML
    return $html;
  }

my $cgi = new CGI;
print $cgi->header;
if ($cgi->param()) {
    if ($cgi->param('doResults') eq "true") {
        sleep(5);
        print html_page('', 'Here are your results!');
    }
}
else {
    my $meta_refresh = '<meta http-equiv="refresh" content="0; /cgi-bin/twoStageScript.pl?doResults=true" />';
    print html_page($meta_refresh, 'PLEASE BE PATIENT');
}
exit;
雄赳赳气昂昂 2024-09-03 18:20:48

终于有一个 Ajax 版本可以工作了。 Slow.pl 文件是需要一段时间才能返回的文件。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title>Two Stage web page demo using Ajax</title>
    </head>
    <body>
        <h1>Two Stage web page demo using Ajax</h1>
        <div id="result">
            Users input form goes here.
            <p>
            <input type="submit" value="Here is your submit button" id="load_basic" />
        </div>
        <script type="text/javascript" src="jquery-1.4.2.js"></script>
        <script type="text/javascript">
        $.ajaxSetup ({
            cache: false
        });
        var ajax_load = "Please be patient, this could take a while. <p> <img src='img/load.gif'/>";

        //  load() function
        $("#load_basic").click(function(){
            $("#result").html(ajax_load).load("/cgi-bin/slow.pl");
        });
        </script>
    </body>
</html>

Finally got an Ajax version working. The slow.pl file is the file that takes a while to return.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title>Two Stage web page demo using Ajax</title>
    </head>
    <body>
        <h1>Two Stage web page demo using Ajax</h1>
        <div id="result">
            Users input form goes here.
            <p>
            <input type="submit" value="Here is your submit button" id="load_basic" />
        </div>
        <script type="text/javascript" src="jquery-1.4.2.js"></script>
        <script type="text/javascript">
        $.ajaxSetup ({
            cache: false
        });
        var ajax_load = "Please be patient, this could take a while. <p> <img src='img/load.gif'/>";

        //  load() function
        $("#load_basic").click(function(){
            $("#result").html(ajax_load).load("/cgi-bin/slow.pl");
        });
        </script>
    </body>
</html>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文