rlm@0
|
1 #!C:/strawberry/perl/bin/perl.exe
|
rlm@0
|
2 use strict;
|
rlm@0
|
3 use CGI::Ajax;
|
rlm@0
|
4 use CGI;
|
rlm@0
|
5
|
rlm@0
|
6 # define an anonymous perl subroutine that you want available to
|
rlm@0
|
7 # javascript on the generated web page.
|
rlm@0
|
8
|
rlm@0
|
9 my $evenodd_func = sub {
|
rlm@0
|
10 my $input = shift;
|
rlm@0
|
11
|
rlm@0
|
12 my $magic = " <font size=-1>look ma, no submit!</font><br>";
|
rlm@0
|
13
|
rlm@0
|
14 # see if input is defined
|
rlm@0
|
15 if ( not defined $input ) {
|
rlm@0
|
16 return("input not defined or NaN" . $magic);
|
rlm@0
|
17 }
|
rlm@0
|
18
|
rlm@0
|
19 # see if value is a number (*thanks Randall!*)
|
rlm@0
|
20 if ( $input !~ /\A\d+\z/ ) {
|
rlm@0
|
21 return("input is NaN" . $magic);
|
rlm@0
|
22 }
|
rlm@0
|
23
|
rlm@0
|
24 # got a number, so mod by 2
|
rlm@0
|
25 $input % 2 == 0 ? return("$input is EVEN" . $magic) : return("$input is ODD" . $magic);
|
rlm@0
|
26
|
rlm@0
|
27 }; # don't forget the trailing ';', since this is an anon subroutine
|
rlm@0
|
28
|
rlm@0
|
29 # define a function to generate the web page - this can be done
|
rlm@0
|
30 # million different ways, and can also be defined as an anonymous sub.
|
rlm@0
|
31 # The only requirement is that the sub send back the html of the page.
|
rlm@0
|
32 sub Show_HTML {
|
rlm@0
|
33 my $html = "";
|
rlm@0
|
34 $html .= <<EOT;
|
rlm@0
|
35
|
rlm@0
|
36 <HTML>
|
rlm@0
|
37 <HEAD><title>CGI::Ajax Example</title>
|
rlm@0
|
38 </HEAD>
|
rlm@0
|
39 <BODY>
|
rlm@0
|
40 <form>
|
rlm@0
|
41 Enter a number:
|
rlm@0
|
42 <input type="text" name="val1" id="val1" size="6"
|
rlm@0
|
43 onkeyup="evenodd( ['val1'], ['resultdiv'] ); return true;"><br>
|
rlm@0
|
44 <hr>
|
rlm@0
|
45 <div id="resultdiv" style="border: 1px solid black;
|
rlm@0
|
46 width: 440px; height: 80px; overflow: auto">
|
rlm@0
|
47 </div>
|
rlm@0
|
48 </form>
|
rlm@0
|
49 </BODY>
|
rlm@0
|
50 </HTML>
|
rlm@0
|
51 EOT
|
rlm@0
|
52
|
rlm@0
|
53 return $html;
|
rlm@0
|
54 }
|
rlm@0
|
55
|
rlm@0
|
56 my $cgi = new CGI(); # create a new CGI object
|
rlm@0
|
57 # now we create a CGI::Ajax object, and associate our anon code
|
rlm@0
|
58 my $pjx = new CGI::Ajax( 'evenodd' => $evenodd_func );
|
rlm@0
|
59
|
rlm@0
|
60 # now print the page. This can be done easily using
|
rlm@0
|
61 # CGI::Ajax->build_html, sending in the CGI object to generate the html
|
rlm@0
|
62 # header. This could also be done manually, and then you don't need
|
rlm@0
|
63 # the build_html() method
|
rlm@0
|
64 print $pjx->build_html($cgi,\&Show_HTML); # this outputs the html for the page
|
rlm@0
|
65
|
rlm@0
|
66 # that's it!
|
rlm@0
|
67
|