ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
19.6 Form GenerationPerhaps you're tired of typing your program's parameter to your browser. Just make a fill-out form instead, which is what most folks are used to. The parts of the form that accept user input are typically called widgets, a much handier term than "graphical input devices." Form widgets include single- and multiline textfields, pop-up menus, scrolling lists, and various kinds of buttons and checkboxes. Create the following HTML page, which includes a form with one text-field widget and a submit button. When the user clicks on the submit button,[7] the ice_cream script specified in the ACTION tag is called.
<!-- ice_cream.html --> <HTML> <HEAD> <TITLE>Hello Ice Cream</TITLE> </HEAD> <BODY> <H1>Hello Ice Cream</H1> <FORM ACTION="http://www.SOMEWHERE.org/cgi-bin/ice_cream"> What's your flavor? <INPUT NAME="favorite" VALUE="mint"> <P> <INPUT TYPE="submit"> </FORM> </BODY> </HTML> Remember that a CGI program can generate any HTML output you want, which will then be passed to any browser that fetches the program's URL. A CGI program can, therefore, produce the HTML page with the form on it, just as a CGI program can respond to the user's form input. Moreover, the same program can perform both tasks, one after the other. All you need to do is divide the program into two parts, which do different things depending on whether or not the program was invoked with arguments. If no arguments were received, then the program sends the empty form to the browser; otherwise, the arguments contain a user's input to the previously sent form, and the program returns a response to the browser based on that input. Keeping everything in a single CGI file this way eases maintenance. The cost is a little more processing time when loading the original page. Here's how it works: #!/usr/bin/perl -w # cgi-bin/ice_cream: program to answer *and generate* ice cream # favorite flavor form (version 3) use CGI qw(:standard); my $favorite = param("flavor"); print header, start_html("Hello Ice Cream"), h1("Hello Ice Cream"); if ($favorite) { print q("Your favorite flavor is $favorite."); } else { print hr, start_form; # hr() emits html horizontal rule: <HR> print q("Please select a flavor: ", textfield("flavor","mint")); print end_form, hr; } If, while using your browser, you click on a link that points to this program (and if the link does not specify Figure 19.2: A basic fill-out formNow fill in the Figure 19.3: Result of submitting the form shown in Figure 19-2 |