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