1. Trang chủ
  2. » Công Nghệ Thông Tin

Prentice hall javascript by example jun 2003 ISBN 0131401629

419 61 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 419
Dung lượng 7,21 MB

Nội dung

EXERCISE C.2 Creating FormsHTML a Create a Web page called Stirbucks that contains a form to order coffee, similar to the order form in Figure C.41 Figure C.41 The Stirbucks Web page order form 1: In the action attribute of the initial tag, specify a URL that directs the server to a CGI script using the default GET method Test your file in a browser The CGI script will print the value of the QUERY_STRING environment variable Processing FormsCGI a Write a CGI script that will send back to the user an HTML page that thanks him for his order and tells him the coffee he selected will be delivered to his shipping address Use the GET method After getting the information from the form, write your own fuction to parse the input Redesign the form to include the POST method The program will test which method 2: was used and call the parse function Create a DBM file that keeps a list of the e-mail addresses submitted When a user submits an order, his e-mail address will be listed in the DBM file Make sure there are no duplicates Design a function to do this The CGI script will handle e-mail Send e-mail to yourself confirming the information that was submitted Design another function to handle e-mail 3: Rewrite the Stirbucks program so that the HTML form and the CGI script are in one CGI program created with the CGI.pm module Use the function-oriented style Add to the Stirbucks program a cookie that will save the user's preferences so that each time he orders coffee, he will get a free sweet If he doesn't state a preference, he will get a bagel with his coffee The bagel or the alternate choice for a free sweet is saved in a Netscape cookie The cookie should not expire for 1 week (See Figure C.42.) Figure C.42 Cookie output 4: Write a CGI script (with the CGI.pm module) that will replace the ATM script you wrote in Chapter 11 The new CGI script will provide a form in the browser that will produce a menu of items; that is, deposit, withdraw, balance, etc Use the object-oriented CGI 5: methods to create the HTML form In the same script, the param function will check which selection was checked, and, based on the selection, the appropriate method will be called from Checking.pm After the form has been filled out and submitted, the results of processing will appear on the same page Chapter 11 The Document Objects: Forms, Images and Links Section 11.1 The Document Object Model Section 11.2 Introduction to Forms Section 11.3 Introduction to Images Section 11.4 Introduction to Links EXERCISES 11.1 The Document Object Model In Chapter 10 we addressed the browser object model The properties and methods of different browsers vary since there is no standard for defining what a browser does The document object model (DOM), on the other hand, deals specifically with a document, and there are now standards that dictate how the objects in an HTML (or XML) page should be represented The DOM is a hierarchical tree-like structure,consisting of a collection of objects, all relating to the document According to the World Wide Web Consortium (WC3), a DOM is a platformand language-independent object model that "allows programs and scripts to dynamically access and update the content, structure, and style of documents."[1] It mimics the structure of the document it models When working with JavaScript, the DOM mimics the HTML document Each element of an HTML document, such as an image, form, link, or button, can be represented as a JavaScript object, and each object contains properties and methods to describe and manipulate these objects (See http://www.w3.org/TR/REC-DOM-Level-1/levelone-html.html for more on HTML-specific DOMs.) [1] World Wide Web Consortium (W3C), http://www.w3.org/DOM/ The W3C abstract states: "The Document Object Model provides a standard set of objects for representing HTML and XML documents, a standard model of how these objects can be combined, and a standard interface for accessing and manipulating them Vendors can support the DOM as an interface to their proprietary data structures and APIs, and content authors can write to the standard DOM interfaces rather than product-specific APIs, thus increasing interoperability on the Web."[2] [2] World Wide Web Consortium (W3C), http://www.w3.org/TR/1998/REC-DOM-Level-119981001/ The W3C defines DOM Level 1 to create an industry standard for all browsers, fully supported by Netscape 6 and Internet Explorer 5 and 6 The standard consists of two parts: the first defines how to navigate and manipulate the HTML and XML structure for the core objects, properties, and methods; the second defines a set of objects strictly related to HTML In addition to DOM Level 1, there are two other levels, still in progress What all that boils down to is that the DOM specifies a standard set of objects that will work with HTML and XML documents no matter what browser, no matter what scripting language Example 11.1 shows an HTML document and how it is represented structurally Example 11.1 (The HTML Document) My Page Level 1 Level 2 Level 3 (The DOM as a Tree) The DOM hierarchya tree structure, similar to a family treeconsists of parents and children called nodes (no, not nerds, but nodes) Each leaf in the tree is called a node The topmost node, the tag, is the root node The and tags are child nodes of the parent node If the nodes are at the same level, they are called siblings, like a real family Nodes may have a parent and a number of child nodes The DOM provides a set of objects, with properties and methods, that allow access to this tree structure within a JavaScript program With the advent of dynamic HTML, the DOM has control over every element of a Web page, and specifies base objects such as Node, NodeList, and NamedNodeMap, and high-level objects to represent all elements of the document We'll see more on dynamic HTML and the DOM in Chapter 15, "Dynamic HTML: Style Sheets, the DOM, and JavaScript." For now we will use the DOM to navigate through the document object and its children, and see how to manipulate these objects with their many properties and methods 11.1.1 The JavaScript Hierarchy Since the JavaScript document objects are arranged in a DOM hierarchy, each node in the tree can be referenced using the dot syntax In JavaScript, the window object is at the top of the tree, the ultimate parent because everything takes place within the window The window is called the top, self, or parent object It has child nodes They are listed below: The navigator object The frames object The history object The location object The document object The screen object The event object We discussed the window as part of the browser object model in the last chapter The DOM is concerned only with those nodes that make up the document object Documents contain text, images, forms, links, etc The most commonly used object is the document object Subordinate to the document object are another set of objects, its children: The anchors object The images object The forms object The links object The applets object The embeds object Figure 11.1 The document model Revisiting the Dot Syntax To refer to an object, you start with the window object (parent), followed by a dot, then the next object in the hierarchy, then another dot, and so on until you reach the desired object; for example, window.location or window.document.forms[0] When referencing a child of the window object it is not necessary to include the window, because JavaScript knows that the window is at the top of the tree Instead of saying window.document.bgColor, you can simply say document.bgColor 11.1.2 The Document Itself The document object is a property of the window object, and if the window is partitioned into frames (subwindows), each frame is a property of the window object Every window (or frame) contains a document object that corresponds to the HTML document shown in the window This object corresponds mainly to the body of the documentthat is, what is inserted between the tagsalthough it can also be found in a limited way within the tags JavaScript programs manipulate this object to bring life to otherwise dead, static pages Since the document object is below the window object, the document object can be represented as a property of the window by saying window.document The forms object is an array of objects below the document object, so the forms object is a property of the document object and is represented as window.document.forms[] As stated before, because the window object is at the top of the hierarchy, any objects just below it, such as the document or location objects, are window properties and the word window is not required; thus, specifying window.document.bgColor is the same as document.bgColor The syntax for describing the background color (bgcolor) property for a document object is shown in the following example: document.bgColor = "yellow"; Document Properties The document object is defined when the HTML tag is encountered on the page and stays in existence until the page is unloaded, and the tag has a number of attributes that define the appearance of the page The document object has properties that correspond to the HTML tag attributes, as shown in Tables 11.1 and 11.2 The properties of environment variable, HTTP_COOKIE By default, the cookie is short-term and expires when the current browser session terminates, but it can be made persistent by setting an expiration date to some later time, after which it will be discarded The path decides where the cookie is valid for a particular server If not set, it defaults to the location of the script that set the cookie The path it refers to is the server's path, where the server's root is / The domain name is the domain where the cookie is valid; that is, the current domain as in 127.0.0.1 or www.ellieq.com Cookies are set in the HTTP cookie header as follows: Set-Cookie: Name=Value; expires=Date; path=Path; domain=Domain Example C.43 #!/bin/perl # A simple CGI script to demonstrate setting and retrieving a c # Run the program twice: the first time to set the cookie on t # client side, and second to retrieve the cookie from the brows # and get its value from the environment variable, # $ENV{HTTP_COOKIE, coming from the server my $name = "Ellie"; my $expiration_date = "Friday, 17-Feb-01 00:00:00: GMT"; my $path = "/cgi-bin"; print "Set-Cookie: shopper=$name, expires=$expiration_date, path=$path\n"; print "Content-type: text/html\n\n"; print param && $query->param('color') ne ""){ $color=$query->param('color') ; # Did the user pick a } elsif ( $query->cookie('preference')){ # Is there a coo # already? $color=$query->cookie('preference'); # Then go get it } else{ $color='yellow';} # Set a default background color if # a cookie doesn't exist, and the user d # select a preference $cookie=$query->cookie(-name=>'preference', -value=>"$color", # Set the cookie -expires=>'+30d', ); print $query->header(-cookie=>$cookie); # Setting the HTTP cookie header 10 print $query->start_html(-title=>"Using Cookies", -bgcolor=>"$color", ); print $query->h2("Example: Making Cookies"); &print_prompt($query); &do_work($query) if ($query->param); print $query->end_html; 11 sub print_prompt{ my($query) = @_; print $query->startform; print "What is your name? "; print $query->textfield(-name=>'name', -size=>30); # A simple text fi print ""; print "What is your occupation? "; print $query->textfield(-name=>'occupation', # Giving -default=>'Retired', # to text -size=>30, -maxlength=>120 ); print ""; print "What is your favorite color? "; print $query->textfield(-name=>'color'); # Giving valu print $query->br(); print $query->submit('action', 'Enter'); print $query->reset(); print $query->endform; print $query->hr(); } 12 sub do_work{ my ($query) = @_; my (@values, $key); print "Here are the settings"; 13 foreach $key ($query->param){ print "$key: \n"; @values=$query->param($key); print join(", ",@values), ""; } } EXPLANATION The module is loaded into this script The CGI module's constructor, new, is called and a reference to a CGI object is returned and assigned to $query We will be using the object-oriented form of CGI.pm in this example If the form was filled out and if the user selected a color, the param function will return true; in other words, if param is not a null string, the value of the selected color will be assigned to the scalar, $color If the form has been filled out, and a cookie was sent back to the server, the value of the cookie will be retrieved and store it in the scalar, $color If the user didn't select a color, and there was no cookie, then the default background will be set to yellow If a cookie was set, retrieve the value of the preference from the cookie The cookie method will extract the value of the HTTP_COOKIE environment variable If this is the first time this script has been run, a default value of yellow will be set for the background color Key/value pairs for the cookie are set The cookie is set to expire after 30 days If no expiration date is set, the cookie is only good for the current session of the browser The header method creates the HTTP cookie The background color for the HTML page is set by the start_html method The method that displays the HTML form is defined The method that parses the form after it has been filled out is defined Each of the key/value pairs produced by the param method are displayed Example C.45 (What the Cookie HTTP header looks like) Set-Cookie: preference=yellow; path=/form1CGI.cgi; expires=Sun, 17-Sep-2000 09:46:26 GMT Figure C.37 The default background color was set to yellow Figure C.38 The user's preference, lightblue, is stored in a cookie C.9.6 HTTP Header Methods A cookie is assigned to an HTTP header as shown in the previous example Table C.18 lists other methods that can be used to create and retrieve information from HTTP headers Table C.18 HTTP header methods HTTP Header Method What It Does accept() Lists MIME types or type auth_type() Returns authorization type for the current session cookie() Creates and retreives cookies header() Returns a valid HTTP header and MIME type https() Returns information about SSL for a session path_info() Sets and retrieves addtional path information path_translated() Returns additional path information query_string() Returns the URL encoded query string raw_cookie() Returns a list of unprocessed cookies sent from the browser redirect() Generates an HTTP header with a redirection request to the browser to load a page at that location referer() Returns the URL of the page the browser displayed before starting your script remote_addr() Returns the IP address of the remote host, possibly a proxy server remote_ident() Returns remote user's login name if the identity daemon is activiated remote_host() Returns the DNS name of the remote host remote_user() Returns the account name used to authenticate a password request_method() Returns the HTTP method, GET, POST, or HEAD script_name() Returns the URL of this script relative to the server's root self_url() Returns the URL of the CGI script: protocol, host, port, path, additional path info, and parameter list; can be used to reinvoke the current script server_name() Returns the name of the Web server server_software() Returns the name and version of the Web server server_port() Returns the port number for the current session (usually 80) url() Returns URL of the current script without additional path information and query string user_agent() Returns browser information user_name() Returns remote user's name if it can virtual_host() Returns the name of the virtual host being accessed by the browser Example C.46 #!/usr/bin/perl use CGI qw(:standard); print header; print start_html(-title=>'Using header Methods'), h1("Let's find out about this session!"), p, h4 "Your server is called ", server_name(), p, "Your server port number is ", server_port(), p, "This script name is: ", script_name(), p, "Your browser is ", user_agent(), "and it's out of date!", p, "The query string looks like this: ", query_string() p, "Where am I? Your URL is: \n", url(), p, "Cookies set: ", raw_cookie(); 10 print end_html; Figure C.39 Output from Example C.46 EXERCISE C.1 The Environment Variables and CGI Create a CGI script that will print to the browser: 1: The name of the server is: The gateway protocol is: The client machine's IP address: The client machine's name: The document root is: The CGI script name is: (Hint: Use the %ENV hash.) Creating A CGI Program a Write a CGI script called town_crier that will contain HTML text and Perl statements The script will contain two subroutines: &welcome and &countem The welcome subroutine will print Welcome Sir Richard!! Use a blue font that blinks the welcome (Note: Internet Explorer ignores blink.) The subroutine will also print today's date (Use the ctime library function.) The subroutine called countem will be written in a file called countem.pl The town_crier script will call countem passing its name (town_crier) as an argument to the subroutine Remember, the name of the script is stored in the $0 variable, e.g., &countem ($0); The subroutine will return the number of times the page has been visited See Figure 10.40 for an idea of how this script will display its output in the browser's window The countem function should be designed to 2: Take an argument the name of the file that called it Unless there is a file called town_crier.log already in the directory, the file will be created Either way, the file will be opened for reading and writing (If the countem function were called from another Perl script, then the log file created would have the name of that script, followed by the log extension.) If the log file is empty, countem will write the value 1 into the file; otherwise a line will be read from the file The line will contain a number The number will be read in and stored in a variable Its value will be incremented by 1 Each time town_crier is executed, this function is called The new number will be sent back to the file, overwriting the number that was there The log file will be closed The countem subroutine will return the value of the number to the calling program (In the example, I put the number in a cell of an HTML table and sent the whole string back to the town_ crier Don't bother to try to create the table if you don't have time Just send back the number.) If running on a UNIX system, use the flock function to put an exclusive lock on the log file while you are using it and will remove the lock when you are finished Figure C.40 Output of the CGI program in Exercise C.1 Appendix B HTML Documents: A Basic Introduction by Joan Murray ... In addition, rather than having the user submit the form, submission can be controlled by JavaScript with its own submit() method And by naming the forms, JavaScript can handle multiple forms and input types, respond to user-initiated events, and call functions to handle... document's background, in this example, silver This property describes the hexidecimal color of links, blue in this example This property describes the hexidecimal color of the text, forest green in this example This displays the date and time when the document was last... a button or enter data in the text box The input in this example won't be processed when the submit button is pressed Nothing will be displayed by the browser Example 11.5 An HTML Form

Ngày đăng: 26/03/2019, 16:29