Giáo trình Learning WML & WMLScript

pdf 195 trang huongle 3370
Bạn đang xem 20 trang mẫu của tài liệu "Giáo trình Learning WML & WMLScript", để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên

Tài liệu đính kèm:

  • pdfgiao_trinh_learning_wml_wmlscript.pdf

Nội dung text: Giáo trình Learning WML & WMLScript

  1. ,TITLE.29551 Page 1 Friday, September 29, 2000 9:54 AM Learning WML & WMLScript www.it-ebooks.info
  2. ,TITLE.29551 Page 2 Friday, September 29, 2000 9:54 AM www.it-ebooks.info
  3. ,TITLE.29551 Page 3 Friday, September 29, 2000 9:54 AM Learning WML & WMLScript Martin Frost Beijing • Cambridge • Farnham • Kửln • Paris • Sebastopol • Taipei • Tokyo www.it-ebooks.info
  4. ,wamTOC.fm.22766 Page v Wednesday, October 11, 2000 10:28 AM Table of Contents Preface xi 1. Introduction to WML 1 A Complete Example 2 Cards 3 Empty-Element Tags 4 Elements 5 Attributes 5 Entities 7 Comments 8 2. WML Variables and Contexts 10 Variable Substitution 11 Setting Variables 15 Browser Contexts 16 3. WML Tasks and Events 17 Tasks 17 Events 23 4. WML User Interaction 28 Problems with Web Interaction 28 Interaction in WAP 29 The Element 30 The Element 33 The Element 37 v Oracle 8i Internal Services for Waits, Latches, Locks, and Memory, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  5. ,wamTOC.fm.22766 Page vi Wednesday, October 11, 2000 10:28 AM vi Table of Contents The Element 37 The Element 38 The Element 40 The Element 42 The tabindex Attribute 42 5. WML Timers 44 Using Timers with WML 44 The Element 46 6. WML Decks, Templates, and Cards 50 The Element 50 The Element 50 The Element 50 The Element 52 The Element 53 The Element 53 7. WML Text and Text Formatting 57 The Element 57 The Element 58 Character Formatting 59 Tables 61 8. WML Images 65 The Element 65 The WBMP Image Format 67 9. Introduction to WMLScript 68 WMLScript with WML 68 What Is WMLScript? 70 10. WMLScript Datatypes, Variables, and Conversions 73 Datatypes and Literals 73 Variables 77 Type Conversion 80 11. WMLScript Operators and Expressions 82 Operand Conversions 82 Assignment Operators 86 Arithmetic Operators 86 Oracle 8i Internal Services for Waits, Latches, Locks, and Memory, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  6. ,wamTOC.fm.22766 Page vii Wednesday, October 11, 2000 10:28 AM Table of Contents vii Bitwise Operators 87 Shift Operators 88 Logical Operators 89 Increment and Decrement Operators 90 Comparison Operators 91 Type Operators 92 The Conditional Operator 94 The Comma Operator 95 Precedence and Associativity 96 12. WMLScript Statements 98 Expressions as Statements 98 Blocks of Statements 99 Conditions 99 Loops 100 Returning from a Function 102 Other Statements 103 13. WMLScript Functions 104 Function Declarations 104 Function Calls 106 Calls to Other Script Units 106 Calling WMLScript from WML 107 Standard Libraries 110 14. WMLScript Pragmas 112 The access Pragma 112 The meta Pragma 113 15. The Lang Library 114 abort 114 abs 114 characterSet 115 exit 115 float 115 isFloat 116 isInt 116 max 117 maxInt 117 min 117 Oracle 8i Internal Services for Waits, Latches, Locks, and Memory, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  7. ,wamTOC.fm.22766 Page viii Wednesday, October 11, 2000 10:28 AM viii Table of Contents minInt 118 parseFloat 118 parseInt 118 random 119 seed 119 16. The Float Library 121 ceil 121 floor 122 int 122 maxFloat 123 minFloat 123 pow 123 round 124 sqrt 124 17. The String Library 126 charAt 126 compare 127 elementAt 127 elements 128 find 128 format 129 insertAt 130 isEmpty 131 length 131 removeAt 132 replace 132 replaceAt 133 squeeze 134 subString 134 toString 135 trim 135 18. The URL Library 136 escapeString 136 getBase 136 getFragment 137 getHost 137 getParameters 137 Oracle 8i Internal Services for Waits, Latches, Locks, and Memory, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  8. ,wamTOC.fm.22766 Page ix Wednesday, October 11, 2000 10:28 AM Table of Contents ix getPath 138 getPort 138 getQuery 139 getReferer 139 getScheme 139 isValid 140 loadString 140 resolve 141 unescapeString 141 19. The WMLBrowser Library 142 getCurrentCard 142 getVar 142 go 143 newContext 143 prev 144 refresh 144 setVar 144 20. The Dialogs Library 145 alert 145 confirm 145 prompt 146 21. Complete Examples 147 Calculator 147 Battleships 154 A. Absolute and Relative URLs 159 B. WAP Gateways and WSP 163 C. Summary of WMLScript Operators 165 D. Serving WAP Content from a Standard Web Server 168 Index 171 Oracle 8i Internal Services for Waits, Latches, Locks, and Memory, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  9. ,wamTOC.fm.22766 Page x Wednesday, October 11, 2000 10:28 AM www.it-ebooks.info
  10. ,ch00.19207 Page xi Wednesday, October 11, 2000 10:22 AM Preface The Wireless Application Protocol (WAP) is an industry-wide specification for applications that operate over wireless networks, with particular emphasis on applications for mobile devices, especially mobile phones. The standards are pub- lished by the WAP Forum, a body formed in June 1997 by Ericsson, Nokia, Motor- ola, and Unwired Planet, which has since been joined by over a hundred other companies, including IBM, Hewlett-Packard, Visa, and Microsoft. According to the WAP Forum’s official statistics, WAP Forum members represent over 90% of cellu- lar-phone manufacturers worldwide. WAP will be supported by many kinds of devices, from simple cell phones similar to those available today to a new generation of “smart” phones with large touch screens and many applications of their own. That’s before we even look at the range of personal digital assistants (PDAs) available, from palmtops to full minia- turized computers complete with keyboards. All will eventually get WAP capabili- ties, either directly from the manufacturer or as some sort of third-party upgrade. Each device has a different kind of display and different methods for user input. The job of the WAP specification is to sort out this mess and provide a common framework to allow applications to run across all these different platforms. Since WAP works in a mobile environment, it also has to contend with the particu- lar problems of wireless networks: low bandwidth (9600 bps or less is common- place), high latency (round-trip times of the order of seconds are not uncommon), and unreliability (someone may be using her WAP phone when the train goes into a tunnel or when she walks past a tall building). Everyone with a mobile phone knows about the reliability problems. These problems are why WAP is necessary. Some people may ask why they can’t just have normal web pages delivered over normal TCP/IP connections, the only difference from their PCs at home being the wireless link. The trouble with the xi This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  11. ,ch00.19207 Page xii Wednesday, October 11, 2000 10:22 AM xii Preface normal web technologies is that they are aimed at high bandwidth and big screens. WAP keeps the Internet model but optimizes each component for a mobile environment. It keeps track of the state of a session in case the connection is lost, provides compressed formats for the transferred data, and handles display- ing of applications regardless of the input and output available. The WAP Stack The term that refers to all the different parts of the WAP specifications is the WAP stack. This is because the components can conceptually be thought of as layers in a stack. The user interacts with the top of the stack, and the communications hard- ware sits below the lowest level. This concept is illustrated in Figure P-1, together with the names of the various specifications involved. User Browser Layer (WAE, WML, WMLScript, WBMP) High-Level Communication Layer (WSP) Low-Level Communication Layers (WTP, WTLS, WDP) Non-WAP Communications Protocols (PPP, IP, SMS, GPRS, . . .) Device Hardware Figure P-1. The WAP stack Going from bottom to top, the lowest layer in the figure contains various proto- cols (the so-called bearer protocols), which aren’t actually part of WAP but which provide the link between WAP and the actual communications hardware: This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  12. ,ch00.19207 Page xiii Wednesday, October 11, 2000 10:22 AM Preface xiii • IP (Internet Protocol) and PPP (Point to Point Protocol) are the two lowest- level protocols in normal dialup Internet access. (Many first-generation WAP devices work by making a normal dialup call and sending the WAP data across a modem link. IP and PPP are used in such a case.) • SMS (Short Message Service) is a feature provided by most digital mobile phone systems that allows short messages to be sent and received across the wireless link. (Users see this as the ability to send short text messages—a bit like email.) It can also transmit binary data and be used for WAP. • GPRS (General Packet Radio System) is a next-generation mobile phone sys- tem that will bring higher bandwidth and permanent network connections to cell phones and other wireless devices. Instead of having to dial into the server, a cell phone will effectively have a permanent Internet connection. GPRS is based on IP. The next layer up includes various low-level WAP communications protocols: WTP (Wireless Transaction Protocol), WTLS (Wireless Transaction Layer Security), and WDP (Wireless Datagram Protocol). WTP and WDP provide low-level glue between the upper levels and the really low-level communications. WTLS pro- vides security services (encryption and authentication). These protocols aren’t rele- vant to normal application programmers: unless you’re designing a browser, you don’t need to know about them. The second highest level in the stack is the high-level communications protocol, called WSP (Wireless Session Protocol). This provides a complete replacement for HTTP (HyperText Transfer Protocol), which is the protocol used between web servers and web browsers. Although you don’t need to know how this layer works, there are one or two features that may be directly useful: these are described in Appendix B, WAP Gateways and WSP. The highest stack level is the WAE (Wireless Application Environment), which is the part that the user actually sees and with which she interacts. The WAE aims to provide a World Wide Web–like model for writing applications, allowing existing web developers to ease the transition to producing content and applications for mobile devices. To achieve this, the WAE incorporates several key features of the Web that you’ll be familiar with, including URLs (like and MIME content types (such as text/html and image/gif. Additionally, it provides similar replace- ments for other features: HTML is replaced with WML (Wireless Markup Lan- guage), and JavaScript is replaced with WMLScript (Wireless Markup Language Script). Almost all WAP applications can be written without using anything out- side of these two languages and WBMP (Wireless Bitmap: the WAP image for- mat), so they form the vast majority of what you as a developer need to know (and the vast majority of this book!). This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  13. ,ch00.19207 Page xiv Wednesday, October 11, 2000 10:22 AM xiv Preface From Server to Client The complete chain of processing that occurs to WAP content on its journey to the user is illustrated in Figure P-2. (This figure omits the details of the communica- tions, since they’re not very important, and they change depending on the precise low-level bearer protocol in use.) Server Server WAP HTTP User WAP Browser WAP Gateway Origin Server Figure P-2. WAP chain of processing The WAP browser in the figure can run on any supported device, from a cell phone to a PDA. Generally, cell phones need to be designed to support WAP, but most modern PDAs can be upgraded to support WAP simply by purchasing the browser software and installing it. PDAs need to be used with a cell phone to pro- vide the connectivity. The origin server (on the far right of the figure) stores or generates the content itself. In nearly all cases, the protocol used to communicate with the origin server is standard HTTP, so this can be a standard web server. It’s usually necessary to make a couple of minor modifications* to the server’s configuration, so it can serve WAP content. All the most popular web-server software can perform this task. An interesting solution is to use a technology such as XSLT (XML Stylesheet Language Transformations), which allows both HTML and WML to be automatically gener- ated from the same raw data. Not included in the picture but quite likely to be present is some sort of backend database server. The origin server uses standard web technologies (such as CGI scripts or Java servlets, for instance) to generate any required dynamic content. These scripts probably need to communicate with a database to get the raw data to output. (This is going beyond the scope of this book, however. All standard * Specifically, modifications include adding support for the WAP content types. The types that need to be added are described in Appendix D, Serving WAP Content from a Standard Web Server. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  14. ,ch00.19207 Page xv Wednesday, October 11, 2000 10:22 AM Preface xv techniques for generating web content on a server will also work for WAP, so you should read a book on one of those.) The WAP Gateway The WAP gateway box in Figure P-2 is the more interesting. The job of the WAP gateway is to convert between the browser’s WAP communication protocols (WSP, WTP, and so on) and the standard HTTP and TCP/IP protocols required by the origin server. It’s also responsible for converting the content output by the origin server (formatted as text) into the compressed binary formats of WML and WML- Script as required by the browser. The gateway consists of some software to do this conversion, usually running on some sort of standard hardware. (Most proper gateways run on heavy-duty Unix servers, but there is low-end gateway software available that even runs on a Win- dows-based PC.) The gateway’s owner must also handle the connection to the bearer network. For a dialup-based bearer, this process is achieved through a stan- dard access server (the same pieces of hardware people use to dial in to the Inter- net), but for such bearers as SMS and GPRS, the connection will probably involve a leased line to a carrier. Because of all these infrastructure requirements, most people offering WAP con- tent will not run their own gateways. (Many people will run their own origin serv- ers, since this is not much different from running a normal web server, but far fewer people will run full WAP gateways.) All cell phone carriers that want to sup- port WAP (which is most of them) will probably run their own gateways, and a number of other portal sites already exist, which also run gateways. Since most of these allow users to connect to any content on the Internet, a user just needs an account on one of these to access all the third-party content available. This Book This book doesn’t aim to cover the low-level details of either the communication protocols (from your perspective, they behave just like HTTP) or the compressed file formats (it doesn’t matter to you how your application gets to the device; all that matters is that it does). I also don’t go into the details of how security and encryption are handled (these are just other parts of the communication process). Most web developers don’t bother to learn how HTTP or TCP/IP work, as they can get by just fine without, and it only distracts them from their real job of writ- ing web pages. If you want to know these details, you can download the latest versions of the specifications from the WAP Forum’s web site ( wapforum.org). This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  15. ,ch00.19207 Page xvi Wednesday, October 11, 2000 10:22 AM xvi Preface Conventions Used in This Book This book uses the following font conventions: Italic Indicates operating-system pathnames; filenames; program names; Internet addresses, such as domain names and URLs; and new terms where they are defined. Boldface Indicates names of GUI items: window names, buttons, menu choices, etc. Constant width Indicates code, command lines, and options that should be typed verbatim; names and keywords in WML and WMLScript programs, including function names and variable names; and XML element tags. Italic constant width Indicates items in code where the user or programmer must supply a name or value. The owl icon designates a note, which is an important aside to the nearby text. The turkey icon designates a warning relating to the nearby text. Comments and Questions The information in this book has been tested and verified, but you may find that features have changed (or you may even find mistakes!). You can send any errors you find, as well as suggestions for future editions, to: O’Reilly & Associates, Inc. 101 Morris Street Sebastopol, CA 95472 (800) 998-9938 (in the United States or Canada) (707) 829-0515 (international/local) (707) 829-0104 (fax) This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  16. ,ch00.19207 Page xvii Wednesday, October 11, 2000 10:22 AM Preface xvii You can also send messages electronically. To be put on the mailing list or request a catalog, send email to: info@oreilly.com To ask technical questions or comment on the book, send email to: bookquestions@oreilly.com There is a web site for the book, where examples, errata, and any plans for future editions are listed. The site also includes a link to a forum where you can discuss the book with the author and other readers. You can access this site at: For more information about this book and others, see the O’Reilly web site: Acknowledgments As ever, this book involves the work of many people besides myself. I am deeply grateful to my editor, John Posner, for his continual constructive criti- cism and innumerable helpful comments. Without them, this book would be vastly inferior. I really can’t emphasize enough how great a help he was. Thanks to Christien Shangraw and Katie Gardner for finding and supplying me with the StarOffice template and for responding patiently to my queries. Thanks are also due to O’Reilly in general, for allowing me the opportunity to write this book. Thanks and apologies must go to my friends, who put up with me cancelling plans weekend after weekend so that I could get some writing done. Thanks espe- cially to all the people who offered to read through the book before I sent it off: sorry that I never got any of it finished early enough to take you up on your offers! A small and select group of people have been particularly understanding in the face of almost complete abandonment to The Book. You know who you are. Thanks to my employer, for allowing me to write the book in the first place and for allowing me time off at short notice when deadlines were approaching. Finally, a special thanks must go to Leon, because of the quantity of beer he promised me if I’d give him a mention. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  17. ,ch00.19207 Page xviii Wednesday, October 11, 2000 10:22 AM www.it-ebooks.info
  18. ,ch01.19333 Page 1 Wednesday, October 11, 2000 10:23 AM Chapter 1 1 Introduction to WML The heart of WAP from the point of view of you, the content developer, is a new markup language called the Wireless Markup Language (WML). If you have worked with the HyperText Markup Language (HTML), much of WML will look familiar but be warned that there are several differences that can easily catch you out. Some of these differences come from WML’s simplicity compared to HTML: many features that are found in HTML are simply not present in WML. To use a common example, HTML gives you great control over the appearance of text within a document: you can change its size, specify the typeface to be used, add styling such as boldface or underlining, and have a fine degree of control over its color. The only controls WML gives you over the text are a few simple styles (emphasis, strong emphasis, boldface, italics, and underlining) and the ability to specify text that is larger or smaller than normal. A further surprise is that most WAP browsers to date don’t even support most of these. Losing this control over appearance that HTML provides forces you to think in a different way about the pages you write, concentrating on content rather than appearance (substance over style, if you like). If you’ve ever designed a web page to be usable under a really old browser (or a text-only browser) as well as the lat- est version of a major browser, you’ll already have a good idea of the sort of things you need to bear in mind. Not all browsers even know about recent HTML such features as tables, frames, or stylesheets, and if you want to support people with those browsers, you have three choices: avoid the new feature altogether, write your pages to work even if the feature isn’t present, or provide multiple ver- sions of your pages and allow the user to select his favorite combination of fea- tures. In the same way, not all WAP browsers support images, tables, or text style 1 This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  19. ,ch01.19333 Page 2 Wednesday, October 11, 2000 10:23 AM 2 Chapter 1: Introduction to WML changes,* and if you rely on them, you reduce the potential audience for your pages dramatically. It’s not all bad, though. While WML does drop many of the features of HTML, it adds some powerful new ones, and because it was designed from the start for interactive applications many of the headaches of the web world simply disap- pear. It also has the advantage of having been designed in one go, rather than having features haphazardly added by different people without any proper overall coordination, which is the case with many of the new features of HTML. A Complete Example Before we discuss WML any further, Example 1-1 displays the time-honored “Hello World.” The code for this example, as well as all the other substantial examples, is available on the book’s web page ( Example 1-1. A Simple WML Example Hello, World! Depending on the browser in use, this may look something like Figure 1-1. Several things need to be explained about this example, but for some of them you’ll have to wait until later chapters. The first thing to note is the special header (the first four lines). This looks confusing, but you don’t actually need to know what it means: just include it at the top of all your WML pages, and all the pro- grams that deal with them will be happy.† The second thing to note is that all tag names are in lowercase (tags are inside angle brackets). This is important: unlike HTML, where , , , * There are several reasons why these features may not be available. One is that some displays may sim- ply be unable to cope with the features. Another reason, which is common at the moment but which will hopefully go away in the future, is that less widely used features were often lost in the rush to get a WAP device out into the market as early as possible. † If you’re familiar with the eXtensible Markup Language (XML), you’ll recognize these lines as the XML prolog for the document. (WML is an XML application, which means that WML documents follow a set of rules laid down in the XML specifications.) If you’re don’t know XML, it doesn’t matter: just copy those four lines and live in blissful ignorance. A number of other parts of WML syntax are also derived from XML: I will point these out as we encounter them. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  20. ,ch01.19333 Page 3 Wednesday, October 11, 2000 10:23 AM Cards 3 Figure 1-1. Example 1-1 displayed in a WAP browser and all refer to the same thing, in WML, tag names are case-sensitive. All current WML tag names are lowercase, so you must enter them that way in your pages. If you’ve seen some HTML, the rest of the WML syntax should look vaguely famil- iar, although the first tag is , not , and there’s that mysterious-look- ing tag. The tag simply starts a paragraph of text (in this simple case, there is only the one). Cards The reason for the tag is that WML structures its content differently from HTML. Instead of a file being a long stream of content, a file of WML represents a This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  21. ,ch01.19333 Page 4 Wednesday, October 11, 2000 10:23 AM 4 Chapter 1: Introduction to WML deck of cards. Only one card is displayed at a time, but you can link from one card to another and store several in a deck in the same file. Each individual card does in fact behave very much like an HTML page, so you can think of a WML deck as being similar to a number of HTML pages all grouped together. It’s good WML style to use decks of cards to group together related information or user interactions. Cards in a deck are all downloaded at the same time, so the user has to wait only once, and the others can be accessed almost instantly. Conversely, it’s bad WML style to overuse cards, cramming too many into a single deck (and hence into a single downloaded file). Even if you think 30 cards of information are all relevant at the same time, the user will get bored waiting for all of them to download before she gets to see the first one. It is hard to put a fixed limit on the number of cards you should use, but here’s a general rule of thumb: if you find yourself using more than five or six cards in a single deck, you should think hard about how your pages are organized. Although you shouldn’t concern yourself too much with the transmission of the content, another thing to bear in mind is that many devices can’t cope with large files. (The Nokia 7110 cell phone, the most popular WAP device in Europe, has trouble if the deck is more than about 1400 bytes after being passed through the gateway.) Empty-Element Tags Now, just to worry all the HTML users some more, check out Example 1-2. Example 1-2. An Interesting Tag You should recognize most of the structure from Example 1-1, and the tag may be familiar from HTML, but look more closely at the end of the tag: note the extra slash. This is required in WML whenever a tag has no matching end-tag. (An end-tag has a slash after the first angle bracket, like .) These so-called empty-element tags are quite common in both WML and HTML, but HTML doesn’t This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  22. ,ch01.19333 Page 5 Wednesday, October 11, 2000 10:23 AM Attributes 5 decorate them in any special way, so they look just like start-tags. This makes some unnecessary work for the browser and any other program that has to read the file, so WML makes the structure more consistent.* Elements An alternative way of thinking about these extra slashes is to think in terms of ele- ments.† An element takes one of two forms: either a start-tag and an end-tag (whose types must match): . . . or a single empty-element tag (complete with extra slash): Note that there is exactly one slash per element. An element can contain other elements (either matched pairs or empty-element tags), possibly mixed up with flow text. Looking at Example 1-2 this way, there is a single element (as a matched pair ), containing a single element (as a matched pair ), containing a single element (also as a matched pair, ), which in turn contains a single element (as the empty-element tag ). It’s important to ensure the tags match properly. Mismatching tags such as: is an error and will prevent the page from being displayed. This should have been written as: Attributes Start-tags and empty-element tags (but not end-tags) may also have attributes. (In Example 1-2, the title on the tag and the src on the tag are both attributes.) Attributes affect the behavior of the whole element, which is why they can’t appear on end-tags (the only purpose of the end-tag is to mark the end of the element). The effects of attributes vary between different elements: the title attribute on the element sets an optional title to be displayed with the card, while the src attribute on the element gives the URL at which the * Again, you may recognize this as another feature WML takes from XML. This feature is critical to XML, and it also makes WML files easier for the browser to read and parse. If you don’t know XML, don’t worry: just remember to add the extra slash whenever there isn’t a matching end-tag. † Looking at the document in terms of elements also comes from XML. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  23. ,ch01.19333 Page 6 Wednesday, October 11, 2000 10:23 AM 6 Chapter 1: Introduction to WML image can be found. You can also add an align="center" attribute to the element, which centers that paragraph of text (if the browser supports the feature). A further slight difference between WML and HTML is in the quoting of attribute values. In HTML, attribute values may appear in single quotes (attr='value'), in double quotes (attr="value"), and most web browsers also allow them to be unquoted altogether (attr=value), although this isn’t strictly valid. WML doesn’t allow unquoted attribute values: all values must appear within either single or double quotes.* Notation for Attributes Within this book, whenever an attribute is described, a brief summary of the type of value it takes is given in parentheses after its name. The following terms are used in these descriptions: string The value can be any string. url The value should be a valid URL. Unless noted otherwise in the description of the attribute, relative URLs (where only part of the URL is given) are OK; these are resolved relative to the current document’s URL. Resolving is the process of taking an incomplete (relative) URL and turning it into a complete (absolute) URL. It is described in detail in Appendix A, Absolute and Relative URLs. number The value should be a nonnegative integer. length The value represents a length on the browser’s display. It can be specified either as a whole number of pixels or as a percentage (which represents a percentage of the width or height of the screen). In either case, the value must not be negative (but may be zero). boolean The value should be one of the strings true or false. Case is important! name The value should be a string containing only letters, digits, dots, colons, hyphens, and underscores. It is better, however, to avoid the dots, colons, and hyphens, and use only letters, digits, and underscores. * The rules for quoting attribute values are another thing that will be familiar to XML users, since WML takes them from XML. If you don’t know XML, just remember you must use either single or double quotes around all attribute values. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  24. ,ch01.19333 Page 7 Wednesday, October 11, 2000 10:23 AM Entities 7 variable The value may contain embedded variable references (see Chapter 2, WML Variables and Contexts, for more information on variables). optional The attribute may be omitted. required The attribute must be present for the element to be processed correctly. Many browsers will refuse to process a deck if required attributes are missing. default The default value for the attribute. This value is used if the attribute isn’t speci- fied on the tag. Only optional attributes can have defaults. Entities The final bit of WML syntax you need before starting on the range of different ele- ments is the entity. You may recognize entities if you’ve ever had to put certain special symbols (quotes, greater than and less than signs, and several others) into an HTML page. Their purpose is to represent symbols that either can’t easily be typed in (you may not have a British pound sign on your keyboard) or that have a special meaning in WML. (For example, if you put a character to end the tag.) Table 1-1 displays the three forms of entities in WML. Named entities are some- thing you may be familiar with from HTML: they look like & or <, and they represent a single named character via a mnemonic name. Entities can also be entered in one of two numeric forms (decimal or hexadecimal), allowing you to enter any Unicode character into your WML. (This doesn’t guarantee that the browser can display it, but at least you can try.) Decimal numeric entities look like ! (Unicode exclamation mark) or £ (Unicode pound sign). Hexadeci- mal numeric entities look like ! or £ for the same two characters (note that 33 decimal is 21 hexadecimal, and 163 decimal is A3 hexadecimal). Table 1-1. Named Entities and Their Equivalents Named Entity Decimal Entity Hexadecimal Entity Character " " " Double quote (") & & & Ampersand (&) ' ' ' Apostrophe (') < < < Less than ( ) This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  25. ,ch01.19333 Page 8 Wednesday, October 11, 2000 10:23 AM 8 Chapter 1: Introduction to WML Table 1-1. Named Entities and Their Equivalents (continued) Named Entity Decimal Entity Hexadecimal Entity Character       Nonbreaking space ­ ­ ­ Soft hyphen Note that all entities start with an ampersand (&) and end with a semicolon (;). This semicolon is very important: some web pages forget this and cause problems for browsers that want correct HTML (most web browsers are forgiving about slightly incorrect HTML syntax, so many common errors slip through). WAP browsers are likely to be stricter about errors like these. The last two entities in the table may require some explanation. When the browser needs to break a long line of text in order to fit it onto the screen, it looks for a suitable point at which to break, such as the gap between two words. Normally, this means that lines are broken at spaces. A nonbreaking space is a special kind of space that doesn’t mark a word bound- ary, and so the browser doesn’t break the line there. Nonbreaking spaces are use- ful when the characters surrounding the space are not normal English text. In some computer typesetting systems, they are also used to make the line breaks in long passages of text fall in places that make the text easier to read, but this is unlikely to be of use with WAP. Soft hyphens are also linked to line breaking, but instead of preventing a break, they mark a place in a long word where a break is permissible (a discretionary hyphen in computer-typesetting parlance). The hyphen is displayed only if the line is broken at that point.* Comments Sometimes you may find that you want to leave a remark in your WML file to remind you how it works at some later date, or you may want to temporarily remove part of a file while you are testing something else. Comments are the answer. A comment starts with the four characters . Everything that appears between these two markers, including tags, body text, entities, and line breaks, is ignored. Here are some examples: * Entities and their different forms are yet another XML feature in WML, although XML allows them to be more complicated than this (you really don’t want to know). HTML users may know that there are many more entities available in HTML, such as © for a copyright symbol, but WML requires that any beyond the few provided be entered using the numeric forms. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  26. ,ch01.19333 Page 9 Wednesday, October 11, 2000 10:23 AM Comments 9 You can’t nest comments. The following doesn’t work: comment. > Moreover, the two characters can’t appear within the body of a comment, only at the end, as part of the > terminator. If for some reason you want the sequence <! in your body text, write it with an entity (which you would have to do for the < anyway): <! You may be worrying about using comments. Surely they end up sending lots of extra data to the browser, and you keep being told how saving bandwidth is really important? Don’t worry: the WAP gateway removes all comments as part of its pro- cessing, so the browser doesn’t even know they exist. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  27. ,ch02.19455 Page 10 Wednesday, October 11, 2000 10:23 AM 2 Chapter 2 WML Variables and Contexts A significant difference between WML and HTML is that WML supports variables. WML variables contain strings, and these strings can be inserted into the body text of the WML document or into the values of certain attributes. The values of vari- ables can be changed under the control of the WML itself and also from within WMLScript functions (more on these later). The names of WML variables can consist of any combination of letters, digits, and underscores, except that the first character must not be a digit. Like most things in WML, variable names are case-sensitive. The following are all examples of legal variable names: a foo __name_with_underscores___ ThisVariableNameIsImpracticalBecauseItIsTooLong xy17 The following are examples of invalid variable names: 17xy (starts with a digit) name with spaces (space is not a letter, digit, or underscore) Although WML doesn’t impose a limit on the length of variable names, remember that the full name needs to be transmitted over a low-bandwidth link and then stored in the (possibly limited) memory on the device running the browser. As a result, it’s a good idea to keep your variable names short. 10 This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  28. ,ch02.19455 Page 11 Wednesday, October 11, 2000 10:23 AM Variable Substitution 11 Variable Substitution Variables can be inserted (or substituted ) into the body text or an attribute value in one of three ways: $name $(name) $(name:conversion) If the first form is used, the variable name must be followed by some character that’s illegal in variable names (any character other than a letter, digit, or under- score). Because of this, it is unwise to use the first form: not only is it less clear than the second, it can also be dangerous, as a minor change to the file (such as removing a space) can change what the browser believes the variable name to be. In addition, some current brows- ers don’t support this form properly. The conversion specified with the third form can take one of three values, each of which can also be abbreviated to its first letter. Unusually for WML, these conver- sion specifiers are case-insensitive: escape or e The variable’s value undergoes URL escaping before it is substituted. This pro- cess replaces certain characters in the value with an escape sequence, consist- ing of a % followed by two hexadecimal digits. In addition, each space character in the value is replaced by a +. For example, if the value of the variable NickNames is Buz, Rocket, then $(NickNames:e) is replaced by Buz%2C+Rocket. (The hexadecimal code for the comma (,) character is 2C.) Note that even though this process is called URL escaping, the value doesn’t have to be a URL: any string can be used. unesc or u The variable’s value undergoes the inverse of URL escaping, known as URL unescaping. This process reverses the steps involved in URL escaping: it replaces sequences of a % and two hexadecimal digits with single characters and each + with a space. For example, if the value of the variable NickNamesE is Buz%2C+Rocket, then $(NickNamesE:u) is replaced by Buz, Rocket. (Note that this has exactly reversed the previous example.) This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  29. ,ch02.19455 Page 12 Wednesday, October 11, 2000 10:23 AM 12 Chapter 2: WML Variables and Contexts noesc or n The value is substituted directly. No conversion is done. If there is no conversion specified ($name or $(name) forms), the browser per- forms a default conversion. This default depends on the context of the reference. If the variable is being substituted into an attribute of type onenterforward, onenterbackward, href,orsrc, then the conversion defaults to escape, because all these attribute values specify URLs to various things (you’ll learn about these in later chapters). In all other contexts (including all substitutions into the body text), the default is noesc. A point to bear in mind (after you’ve read Chapter 3, WML Tasks and Events, and Chapter 7, WML Text and Text Formatting) is that attributes of types onclick and ontimer default to noesc, although you might expect them to default to escape like onenterforward and onenterbackward do. Because of these inconsistencies, wise WAP developers always specify a conversion explicitly (even if the conversion is noesc) when substituting variables into attribute val- ues, particularly when those values store URLs. To illustrate these conversions, suppose the variable user contains the value fred, and greeting contains Hello, world!. Then the attribute: title="Welcome, $(user)! $(greeting)" becomes: title="Welcome, fred! Hello, world!" Similarly, the attribute: href="/cgi-bin/login?u=$(user)&g=$(greeting)" is equivalent (because the default conversion of variables within an href attribute is escape) to: href="/cgi-bin/login?u=$(user:e)&g=$(greeting:e)" which then becomes: href="/cgi-bin/login?u=fred&g=Hello%2C+world%21" once variables are substituted. Note that this last example would have been better written using its more explicit form (using :e), rather than relying on the browser to perform default conversion. Note also the use of & to include a & in the URL value. A common mistake (and one that even experienced developers make from time to time) is to write just & and then spend hours trying to figure out why it doesn’t work properly. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  30. ,ch02.19455 Page 13 Wednesday, October 11, 2000 10:23 AM Variable Substitution 13 Empty Variables You may wonder what happens if you try to substitute a variable that has not been defined: does it cause an error? Does anything happen at all? The simple answer is that any undefined variable is equivalent to the empty string, so: foo$(undefined)bar becomes: foobar after variable substitution. In addition, assigning the empty string to a variable removes it from the browser context (see the section “Browser Contexts” later in this chapter). Caveats of Variable Substitution You may be wondering how, if a $ starts a variable, you can put a literal $ into the page or an attribute value. For example, you may want to display the string: Price: $17.00 You may think that entities are the answer: maybe you could just put in $ to make it work. Unfortunately, it doesn’t, due to the way WML browsers handle vari- able substitution. What happens is that the browser goes through the document replacing all the entities with the characters they represent, before it even starts to look for variable references. While $ does indeed represent a $, the browser then interprets this $ as the start of a variable reference, which is exactly what you don’t want to happen! (See the sidebar, “WML Variables and XML,” for a further discussion.) Fortunately, there is a way out. The sequence $$ always represents a single $ when it appears in body text or attribute values. Thus the correct way to display the string Price: $17.00 is: Price: $$17.00 This also means that the sequence $$(foo) represents the six characters $(foo) and not any sort of variable reference. The sequence $$$(foo) represents the character $ followed by the contents of variable foo with the default conversion. A single $ by itself (not followed by another $,a(, or the start of a variable name) is illegal. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  31. ,ch02.19455 Page 14 Wednesday, October 11, 2000 10:23 AM 14 Chapter 2: WML Variables and Contexts WML Variables and XML The reason you can’t work around WML variables with entities lies with the relationship between WML and XML. WML is designed so that a generic XML parser can process the page. The parser takes the source file and make a single pass over it, turning all the elements into a tree structure, with the body text interspersed. Entities are expanded in the same single pass, so that the body text in the tree doesn’t contain any spe- cial XML syntax: it is just simple text. XML doesn’t treat WML variables specially; at this point the sequence $(foo) is just a six-character string. Only after this XML-level parsing is complete does the WML parser get to see the page and handle WML variables. By this time, all $ entities have become simple $ characters, which the WML parser considers to be the start of a variable reference. This situation also explains why you can’t change the page structure with vari- ables: the structure of the page is defined at the XML level using tags and attributes; WML variables are handled later. If the XML parser finds a $ charac- ter in a tag or attribute name, it simply rejects the document. $ isn’t a legal name character in an XML name. It’s necessary to write a single $ as $$ even in attribute values that don’t allow variables. This is because the browser checks all attribute values for variables, even if there shouldn’t be any variables there, and will probably complain if it finds any in the wrong place. Another thing to watch out for is that you can’t change the actual structure of the page using variables. You can change text in between tags, and you can change some attribute values, but you can’t add any new tags or attributes. If the variable img contains the value , then the text: some text$(img)some more text is simply equivalent to the string: some text some more text and not to two separate strings with an image in between. The following tags are both illegal no matter what the value of the foo variable is: This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  32. ,ch02.19455 Page 15 Wednesday, October 11, 2000 10:23 AM Setting Variables 15 If you really need to make changes to the structure of the page like that, you have to do it on the server. Setting Variables You now know just about everything there is to know about actually using WML variables, but one thing you don’t yet know is how to put useful values into the variables in the first place! Actually, there are three ways. The most common is through the use of the vari- ous user interface elements, which are described in Chapter 4, WML User Interac- tion. Variables can also be set from WMLScript, as explained in Chapter 19, The WMLBrowser Library. The third way is with the element. The Element This element must be placed within a task element (described in Chapter 3). Its purpose is to represent an assignment to a WML variable. This assignment takes place when the task is executed. Attributes of the element name (required; variable string) Specifies the name of the variable to be set value (required; variable string) Specifies the new value for the variable For example, the element: creates a variable called var, containing the string foo. If a variable called var already exists, this changes its value to the string foo. Order of Operations in Setting Variables Before executing one or more elements within a task, the browser first expands all variables in all the name and value attributes. Note that this makes the order of the elements within a task unimportant. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  33. ,ch02.19455 Page 16 Wednesday, October 11, 2000 10:23 AM 16 Chapter 2: WML Variables and Contexts To illustrate this behavior, imagine that the variable x contains the value one, y contains two, and z contains three. Now suppose a task contains these three elements: The browser first substitutes all the variables: Finally, the browser assigns the new values to the three variables. Note that this principle of substituting variables first extends to both the name and value attributes of the element. For example, if the variable category has the value color, and variable choice has the value green, then: becomes: This form (with variables in the name) isn’t used often, but it’s worth knowing that it exists. Browser Contexts The browser context in WML is the set of all variables currently set, together with the history stack (the list of all the cards the user has recently visited). The context is emptied (all variables are unset, and the stack is emptied) when a card is displayed with the newcontext attribute set to true. See Chapter 6, WML Decks, Templates, and Cards, for more on cards and their attributes. In addition, whenever the user sends the browser to a new location that wasn’t referenced in the current card (for example, by selecting a bookmark, entering a new URL, or viewing an initial home card), a new context is created. Some brows- ers support multiple contexts, in which case it may be possible to get back to the previous context somehow. But many support only one, meaning that this is equivalent to emptying the context permanently. This new context action doesn’t happen if the new URL came from executing a task, only if it came from some external source. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  34. ,ch03.19577 Page 17 Wednesday, October 11, 2000 10:23 AM Chapter 3 3 WML Tasks and Events In the last chapter, you learned about variables in WML, something not found in HTML. This chapter covers two further parts of WML—tasks and events—that have no real equivalent in HTML. (In some cases you can use JavaScript to achieve simi- lar effects.) Tasks A WML task is an element that specifies an action to be performed by the browser, rather than something to be displayed. For example, the action of changing to a new card is represented by a task element, and the action of returning to the previous card visited is represented by a task element. Task elements encapsulate all the information required to perform the action. Tasks are used in many places in WML. Events (discussed later in this chapter) are tied closely with tasks, and many of the user interface elements (see Chapter 4, WML User Interaction) use tasks to perform actions. To see how tasks are used in context, consider the element , which repre- sents some sort of control that the user can activate, such as a softkey, a menu item on a cell phone, or maybe even an onscreen button if the device has a touch- screen. A element isn’t itself a task element. Rather, it contains a task subele- ment that specifies the action to perform when the user activates the control. A element that, on activation, simply assigns the value wibble to the vari- able test can be written as: 17 This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  35. ,ch03.19577 Page 18 Wednesday, October 11, 2000 10:23 AM 18 Chapter 3: WML Tasks and Events To have the same element instead send the browser to a card called card2 in the current deck, you could write: Note that the element is exactly the same for these two examples. The only difference is the task element (the or the ). This added consis- tency (or orthogonality to use the technical term) is an important benefit of using tasks. The element is explained more fully in Chapter 4. Tasks and Variables All tasks can change variables in the browser’s context using the ele- ment, as described in Chapter 2, WML Variables and Contexts. The new variable bindings don’t affect the task itself but rather take effect when the task completes. For example, suppose the variable page contains the value login. The task: goes to login.wml, not bad.wml, because the browser substitutes the original value of the page variable into the href attribute before it assigns the new value to the variable. The Task As the name suggests, the task represents the action of going to a new card. (It is also used for a special purpose with WMLScript, but you must wait until later in the book to find out about that.) The task takes several different attributes to customize exactly how to find the new card. Usually, only href and sometimes method attributes are used. Attributes of the task href (required variable url) Gives the URL of the new card. Relative URLs are resolved relative to the cur- rent card (the one containing this ). This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  36. ,ch03.19577 Page 19 Wednesday, October 11, 2000 10:23 AM Tasks 19 method (optional string; default get) Specifies the method that should be used to fetch the deck. This must be one of the values get or post, corresponding to the GET and POST methods of HTTP. sendreferer (optional boolean; default false) If set to true, the browser sends the URL of the current deck along with the request. This URL is sent as a relative URL if possible. The purpose of this is to allow servers to perform simple access control on decks, based on which decks are linking to them. For example, using HTTP, this attribute is sent in the HTTP Referer header. accept-charset (optional string; default unknown) Specifies a comma- or space-separated list of character sets that can encode data sent to the server in a POST request. The browser selects one to use when sending the data. If this is set to the value unknown (the default), the browser uses the same character set that sent this document to the browser. (Note that this attribute is an advanced feature and is rarely used.) The method attribute: GET and POST One of the more interesting options available on the task is the method attribute. This specifies whether the request should be sent as a GET or as a POST. This option is used only when sending information for processing on the server: it’s not used when simply fetching static pages of WML. If you know HTML, you may recognize similarities with the METHOD="GET" and METHOD="POST" attributes that can be put on an HTML element. WML puts this attribute on the task instead, but it has essentially the same effect. GET is the normal method used in HTTP. All the information sent to the server is encoded in the URL, and the server uses this URL to find some resource and return it to the browser. The main advantage of GET is that it’s simple. Any information is simply added to the query part of the URL (more on the parts of URLs in Appendix A, Absolute and Relative URLs). You can even put the query information directly into the URL using variables. The main disadvantage of GET is that it can be used only for a limited amount of data. Web servers and other programs that process URLs impose certain limits on the length of a URL they are prepared to handle. This limits the size of the request that can be sent using GET. A subtler problem with GET relates to the fact that all the information you send becomes part of the URL. Many browsers display the URL of the current deck This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  37. ,ch03.19577 Page 20 Wednesday, October 11, 2000 10:23 AM 20 Chapter 3: WML Tasks and Events somewhere on the screen (even if only briefly), and most web servers store the entire URL in their log files, complete with the extra data from the GET. If this information is of a sensitive nature (a password, for example), it’s displayed on the screen and then saved for posterity in the web server’s logs! The POST method avoids these two problems, by sending the data separately from the URL in the request. As a result, the URL stays small, and the browser display and web server logs don’t contain any of the data. The element In modern versions of WML, information to be posted with the POST method is specified in elements within the element. This information takes the form of a list of name/value pairs. Each element specifies a single pair. The element is very simple, having only two attributes: name (required variable string) The name of this field value (required variable string) The value of this field WML allows elements to be used even with the GET method. In this case, the fields are added to the end of the query part of the URL. For example, consider the task: This has the same effect as: Using the element in this way can make your WML much clearer and also makes your life much easier if you have to change the WML to use POST at some point in the future. You can even mix the two styles. Here’s another way to write exactly the same task as the last two examples: Shorthand forms of tasks One form of task is more common than any other: a task that has no attributes other than href and doesn’t contain any or This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  38. ,ch03.19577 Page 21 Wednesday, October 11, 2000 10:23 AM Tasks 21 elements. Because this form is so common, WML provides a shorthand form you can use in many situations. Instead of including the task as a complete element, the value that would be put into the href attribute of the element is simply included as an attribute on a different element. For example, it is possible to bind a task to an option in a selection list, so that the task is performed when the option is selected. The nor- mal way of doing this looks like this: Option text Using the shorthand form, this can be written as: Option text I think you’ll agree, that’s much shorter and clearer. This is allowed for the onenterforward, onenterbackward, and ontimer attributes of the element; the onpick attribute of the element; and the href attribute of the element. These elements are all described later in this book: don’t worry about them for now. The Task The task represents the action of returning to the previously visited card on the history stack. When this action is performed, the top entry is removed from the history stack, and that card is displayed again, after any variable assignments in the task have taken effect. The task takes no attributes. Most uses of the task are very simple. Usually no variables are involved, and so most tasks are simply: A task is most commonly used in connection with a element (described in Chapter 4). Some browsers don’t provide a back button unless one is specified in the WML, and so a great deal of WML contains the construct: This simply provides a button or some other user-interface construct, which when activated, sends the browser to the previous card. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  39. ,ch03.19577 Page 22 Wednesday, October 11, 2000 10:23 AM 22 Chapter 3: WML Tasks and Events One situation where it can be useful to include variables in a task is a login page, which prompts for a username and password. In some situations, you may want to clear out the password field when returning to the login card, forc- ing the user to reenter it. This can be done with a construct such as: The Task The task is the simplest task that actually does something. Its effect is simply to perform the variable assignments specified by its elements, then redisplay the current card with the new values. The and tasks perform the same action just before displaying the new card. The task doesn’t take any attributes. The task is most often used to perform some sort of “reset” action on the card. Example 3-1 shows how this could be done. The elements prompt the user to enter strings and then store the strings into the variables speci- fied in their name attributes (see Chapter 4 for more information). There is also a task using the POST method to submit the login and password information to a server for processing. Example 3-1. A Reset Button Login: Password: This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  40. ,ch03.19577 Page 23 Wednesday, October 11, 2000 10:23 AM Events 23 Example 3-1. A Reset Button (continued) The Task The purpose of the task is to do nothing (no operation). This may seem particularly useless: why would anyone want a task that doesn’t do anything? The only real use for this task is in connection with templates (discussed in more detail in Chapter 6, WML Decks, Templates, and Cards). However, it can also be specified anywhere a task is required. The task is the only exception to the rule that tasks can set variables. It can’t set variables and can’t even contain any elements. If you want a task to just set variables and not change the current card, use the task. The task doesn’t take any attributes. Because the task takes no attributes and can’t even contain any elements, it always looks the same in use: Events An event in WML is simply something that can happen to some element from time to time. For example, entering a element triggers an event on the , and selecting an from a selection list triggers an event on the . You can harness these events by binding them to a task. The usual way of doing this is with the element. As mentioned earlier in this chapter, for sim- ple tasks you can usually make use of a simpler form: this will be men- tioned when when we discuss the elements in question. For example, the element (detailed in Chapter 4) declares an item in a list of selections. When this item is selected, it triggers an onpick event on the element. Suppose the element were declared without an event handler, like this: Purple This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  41. ,ch03.19577 Page 24 Wednesday, October 11, 2000 10:23 AM 24 Chapter 3: WML Tasks and Events In this case, the onpick event is ignored, since there is no handler. If, on the other hand, the option is declared as: Purple the onpick event is handled by executing the task, sending the browser to a new card. The Element The element declares an event binding. It can’t contain anything except a single task element that is performed when the event occurs. It may be present inside either an element (see Chapter 4) or a element (see Chapter 6). In either case, the element (or elements) must be the first elements declared inside their enclosing element. The element takes only one attribute: type (required string) Gives the type of event to which the task should be bound. For example, use type="ontimer" to bind to the ontimer event of a element. Card Events Sometimes, you may want to do something special when the user enters a particu- lar card. For example, you may want to initialize the values of variables so that the display looks correct. Another thing you may want to do is to clear out some vari- ables when the user returns to a particular card in the history stack. To make this possible, WML defines two events, onenterforward and onenterbackward, which happen on a element when the user enters it. Which event occurs depends on how the card was entered. The onenterforward event The onenterforward event occurs when a card is entered in the forward direc- tion. Entering as a result of a task, selecting a bookmark, or entering a URL directly are all in the forward direction. The most common use of this event is to initialize things that must be set up before the card is displayed, often by using a task or by using a task to run some WMLScript (see “Calling WMLScript from WML” in Chapter 13, WMLScript Functions). This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  42. ,ch03.19577 Page 25 Wednesday, October 11, 2000 10:23 AM Events 25 Example 3-2 shows how this can be used. When the first card is entered forwards, the task is performed, which initializes the state variable. This vari- able can then be updated by other WML pages and is passed through to the server by the task. Example 3-2. Initialization on Entry If the task bound to the onenterforward event is a simple task without or elements, you can use the shorthand form introduced earlier in this chapter: just add an onenterforward attribute to the ele- ment. The value of this attribute is the destination URL. For example, the event binding: is equivalent to the shorter form: This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  43. ,ch03.19577 Page 26 Wednesday, October 11, 2000 10:23 AM 26 Chapter 3: WML Tasks and Events It’s your choice to use the shorthand form, but it means less typing and results in less data being sent to the browser. Be warned that not all tasks you can bind to the onenterforward event actually make sense. For example, the event binding: makes it impossible for the user to enter the card at all: as soon as she went to the card, the browser would immediately return to the previous one! To make matters worse, the event binding: means that as soon as the browser entered the card, it would be immediately redirected to the same card, which would cause an immediate redirect to the same card, and again, and again. . . . Well-written browsers may notice this and signal an error, but not all browsers are well-written: many simply lock up or even crash. The onenterbackward event The onenterbackward event is the companion of the onenterforward event for the backward direction. This event is triggered when the card is returned to as the result of a task or some other action that navigates backwards in the his- tory stack. The most common use for the onenterbackward event is to reset state back to some initial value when returning to the beginning. Example 3-3 alters Example 3-1 to illustrate this: instead of an explicit reset button, the login and password are cleared when the user returns to this card via the history stack. Example 3-3. Reset on Reentry This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  44. ,ch03.19577 Page 27 Wednesday, October 11, 2000 10:23 AM Events 27 Example 3-3. Reset on Reentry (continued) Login: Password: Just as with the onenterforward event, onenterbackward also has a shorthand form in the case where the task is a simple form of , meaning that the event binding: is equivalent to: This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  45. ,ch04.19703 Page 28 Wednesday, October 11, 2000 10:23 AM 4 Chapter 4 WML User Interaction The previous two chapters described some of the features found in WML that don’t exist in HTML. This chapter covers the features that WML provides to receive input from the user, and most of these are much more powerful than their equiva- lents in HTML. The main reason for this extra power is that WML has variables. In HTML, you can have controls such as pulldown menus or text input fields, but you can use these in only limited ways: in an HTML form, which allows you to collect a number of controls and send their results to a server for processing, or with Java or JavaScript, which are complete programming languages built into the web browser. Problems with Web Interaction Using HTML forms for this purpose suffers from one major problem: the process- ing has to be done on the server. The client displays the controls, collects their results, packages them, and sends them to the server, but that’s it. Apart from some simple constraints such as the maximum length of the text in an input box, you can’t even check the input for validity before sending it off. This results in a lot of extra network connections, slowing things down a lot, even on a fast Inter- net link. Imagine how slow all those extra network connections are on a much slower link, as WAP has to contend with. Using Java or JavaScript to collect the input does allow local processing, but they come complete with their own sets of problems. For a start, they both require a lot more from the browser: most older browsers have either no support for these or very limited or buggy support, which makes it harder to write pages that work across all browsers. Most text-only browsers don’t support these at all. (Yes, some people do still use text-only browsers.) 28 This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  46. ,ch04.19703 Page 29 Wednesday, October 11, 2000 10:23 AM Interaction in WAP 29 Another, subtler problem with the Web’s way of doing these things is that there are multiple ways to declare the controls. Suppose you want to display a text input box. Using a form, you can use something like: Using JavaScript with the HTML, possibly: If using Java applets, something like:* TextField wibble = new TextField (); add (wibble); Each of these fragments has to be referenced in a completely different way from within the HTML page that forms the skeleton. Furthermore, the same control has to be added to the page in three different ways, even though they are all drawn in the same way by the browser, and the user interacts with each in the same way. This makes it hard to change the action of a control once it has been imple- mented. It requires rewriting everything related to that control, and probably restructuring the whole page as well. Interaction in WAP For comparison, here is how the same text input box is described in WML, where its result is sent directly to the server: Here, its result is passed to some WMLScript to check it for validity before passing it to the server: Here, it’s displayed to the user in another card for confirmation purposes, without any server transactions involved: These three examples are identical because the same control is always written in the same way in WML. Doing it this way works because none of the controls ever perform any direct action. They are instead linked to the lower-level layers of WML, such as variables and tasks. * It isn’t completely fair to compare Java with HTML here, since Java is a full-featured programming lan- guage, and HTML is just a markup language. But since Java is often used to implement this sort of thing on web pages, it’s appropriate to mention it here. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  47. ,ch04.19703 Page 30 Wednesday, October 11, 2000 10:23 AM 30 Chapter 4: WML User Interaction For example, in the previous element, the only effect of the user enter- ing some text into the box is that the variable wibble is set to a new value. The browser doesn’t directly send the text to the server or call any scripts: it’s up to you to use the value of this variable at some point. The Element Let’s start our exploration of WML’s mechanisms for user interaction with the element, since we’ve just seen it in action. This element is used whenever the user needs to enter a string or some other piece of text. Usually, this should be kept as short as possible, since many WAP users use cell phone keypads to enter these. Entering the letter S on a computer keyboard is easy, but this requires four keypresses on most cell phones. Symbols are even worse: with the exception of a few, such as . and +, symbols are very time-consuming to enter. The element can also be used to enter passwords or other sensitive information. In these cases, the element can be configured to not display the text as it’s being entered. (In the case of cell phones, most display each character for a short time but then replace it with a * or other symbol.) This element is also used for entering numbers. In cases like this, where the range of characters is restricted, it’s possible to set a format for the string, which may speed up input. To do so, set the format to allow only digits; a cell phone knows that the keys don’t need to cycle through all the letters before offering a digit (the digits are accessed with a single keypress instead of four or more). This element (as with all user interaction elements) may be put anywhere in nor- mal paragraph text (namely, inside a element). It takes nine* attributes, most of which are optional. Attributes of the Element name (required name) Gives the name of the variable that gets the text from this element. When the element is displayed, it’s initialized to the contents of this variable if it’s set. If * Strictly speaking, all WML elements may have three standard attributes, id, class, and xml:lang. Apart from one special use of the id attribute on the element, the id and class attributes are intended for use in server-side applications, are ignored by the browser, and won’t be mentioned again. The xml:lang attribute specifies “the natural or formal language” (to quote from the WML specification) of the element: its content is an abbreviation for a particular language (such as en for generic English). This is supposed to influence the display of the elements contained within (for example, certain lan- guages are written right to left rather than left to right), but it’s not implemented by any current brows- ers, and hence won’t be mentioned again. If this all sounds confusing, just forget it: everyone else does. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  48. ,ch04.19703 Page 31 Wednesday, October 11, 2000 10:23 AM The Element 31 it isn’t, the element is initialized to the value of the value attribute if present; otherwise it’s initially empty. type (optional string; default text) If omitted or set to text, indicates that this element doesn’t receive sensitive data, and that the text should be displayed as normal. If set to password, specifies that the text should be obscured in some way. This is normally done by replacing all the characters with some fixed character when displaying the contents. Any other value is illegal. value (optional variable string; default empty) Gives an optional initial value for the text in the element. This default is used only when the variable given by the name attribute isn’t set. If that variable contains a value, its value initializes the element instead. format (optional string; default *M) Gives an optional format for the value. This format can display static text in the input area and can restrict the range of characters that may be entered. A smart browser uses this attribute to speed user input. A format attribute con- taining illegal codes is ignored. The legal codes are: A Any uppercase letter or symbol (not a digit). a Any lowercase letter or symbol (not a digit). N Any numeric character (digit or decimal points). X Any uppercase character. x Any lowercase character. M Any character: uppercase characters may be offered first, but anything is permitted. m Any character: lowercase characters may be offered first, but anything is permitted. *f Any number of characters (zero or more) matching format code f (where f is one of the previous format codes: A, a, N, X, x, M,orm). This may be specified only once and must be at the end of the string. nf Entry of exactly n characters (where n is a digit from 1 to 9), each match- ing format code f. This may be specified only once and must be at the end of the string. This is equivalent to using n occurrences of code f. \c Forces character c to be displayed in the text entry field. This character is displayed within the field and is passed through into the value. For example, the format code NNN\-NNNN matches local North American tele- phone numbers (such as 555-1234). This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  49. ,ch04.19703 Page 32 Wednesday, October 11, 2000 10:23 AM 32 Chapter 4: WML User Interaction Beware, however, of working too many assumptions such as this into your WAP decks, as different countries have different formats for things such as telephone numbers. emptyok (optional boolean; default false) If set to true, specifies that an empty string is a valid input, even if the format attribute otherwise prevents this. If the format string allows an empty input, that takes precedence, and emptyok is ignored. Since the default value for format allows empty input anyway, this attribute has no effect if no format attribute is given. size (optional number) Provides a hint as to how many characters wide the text input should be drawn, if the browser supports it (if it doesn’t, this is ignored). This value doesn’t limit the number of characters that can be entered into the element; for that, see the maxlength attribute. maxlength (optional number; default unlimited) Specifies the maximum number of characters that may be entered into this ele- ment. title (optional variable string) Gives a title to this element, which some browsers may use in its presentation. tabindex (optional number) Provides a hint to the browser about the order in which the user should be allowed to cycle through the elements. This attribute is described fully in the section “The tabindex Attribute” later in this chapter. Examples of the Element Example 4-1 shows how a typical login page asking for a username and password can be constructed. The username is forced to consist entirely of lowercase let- ters, and the password is obscured when it’s entered. Then there is a ele- ment (explained later in this chapter), containing a task. The effect of these last two is to add a button or similar control to the card, which sends the browser to the URL from the href attribute of the go task when it’s activated. Example 4-1. A Login Page This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  50. ,ch04.19703 Page 33 Wednesday, October 11, 2000 10:23 AM The Element 33 Example 4-1. A Login Page (continued) Username: Password: The Element The other high-level control that WML provides is one allowing selection from a list of items. This replaces many different types of control, such as scrolling select- able lists, pulldown menus, and lists of checkboxes. In its simplest form, the element provides an iname attribute giving a WML variable name. Inside the is a list of elements. Select- ing an option sets the iname variable to the index of that item within the , starting from 1. For example: Lizard Spider Squid Selecting Lizard sets animal to 1, selecting Spider sets it to 2, and selecting Squid sets it to 3. In a slightly more complex form, the element has a name attribute rather than iname, and a list of elements, each of which has a value attribute. Selecting one of these options sets the name variable to the contents of the option’s value attribute. For example, a list allowing the user to select a Lon- don airport can be written as: London Heathrow London Gatwick London Stansted London City London Luton Selecting an option sets airport to the corresponding three-letter airport code. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  51. ,ch04.19703 Page 34 Wednesday, October 11, 2000 10:23 AM 34 Chapter 4: WML User Interaction Attributes of the Element title (optional variable string) Provides an optional title for the element, which some browsers may use in its presentation. Others may ignore it. iname (optional name) Specifies a WML variable to be set to the index of the selected item. If this is specified and the variable is already set to an index value, it selects the default value. This takes precedence over ivalue, name, and value for determining the default value. ivalue (optional variable number) Specifies the index of the value that should be the default if the iname attribute isn’t present or its variable isn’t set. This takes precedence over name and value for setting the default. name (optional name) Specifies a WML variable to be set to the contents of the value attribute from the selected option. This may also be used to determine the default value. (The first whose value matches the contents of this variable is selected but only if iname and ivalue have failed to select an item.) This takes precedence over only value. value (optional variable string) Specifies the default value of the . The first item with a value attribute matching this is selected. This attribute is used only when iname, ivalue, or name haven’t managed to select a default value. multiple (optional boolean; default false) If set to true, indicates that this should allow more than one to be active at a time. In this case, the behavior of the name, value, iname, and ivalue attributes changes slightly. (More on this in the section “Multiple Selection,” later in this chapter). tabindex (optional number) As with , this provides a hint to the browser as to how it should cycle through all the controls in the card. See the section “The tabindex Attribute” later in the chapter for more on tabindex. Multiple Selection When a item has a multiple="true" attribute, it allows more than one item to be selected from the list simultaneously. Such a treats the values of the name, value, iname, and ivalue attributes differently than normal. Instead of each representing a single item (either an index or something matching This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  52. ,ch04.19703 Page 35 Wednesday, October 11, 2000 10:23 AM The Element 35 an option’s value), each is treated as a list of values separated by semicolons. (This has the minor side-effect that semicolons are not valid in the value attributes on any in a multiple-selection .) The actual order of the values between the semicolons isn’t defined by WML. For example, a WAP pizza delivery service could use something similar to Example 4-2 to let people choose the toppings for their pizza. Note that this doesn’t allow people to select the same topping more than once. If they want that, they can phone in the order! Example 4-2. Multiple Selection Choose your toppings: Pepperoni Ham Spicy Beef Anchovies Chillies Olives Mushrooms If I then decide that I want a pizza with all these toppings except anchovies, the variable toppings is set to p;h;b;c;o;m,orm;o;c;b;h;p,orb;c;h;m;o;p,or any of the 717 other combinations of those six items. (No, I’m not going to list them all.) If there had been an iname as well as (or perhaps instead of) the name, the vari- able it referenced is set to 1;2;3;5;6;7 or a permutation of those values. In single-selection lists, however, the character ; is valid in option values. Example 4-3 shows Example 4-2 extended with an earlier card offering set pizzas and the chance to customize them by adding and removing toppings. Note that the option of going back from the second card to the first isn’t provided here. This is because the values in the toppings variable may not be in the same order as This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  53. ,ch04.19703 Page 36 Wednesday, October 11, 2000 10:23 AM 36 Chapter 4: WML User Interaction they were when the first initialized them, because their order is not fixed after a multiple selection. Example 4-3. Mixed Selections Choose a Pizza: Plain Pepperoni Supreme Full House Vegetarian Customize your Toppings Pepperoni Ham Spicy Beef Anchovies Olives Mushrooms Chillies This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  54. ,ch04.19703 Page 37 Wednesday, October 11, 2000 10:23 AM The Element 37 The Element While on the subject of the element, it’s time for a closer look at the element that is so vital to it. You’ve already seen the two most com- mon ways to use this element (with or without a value), but it’s also possible to bind a task to an option, so that the task is performed when the user selects the option (or deselects it, for a multiple-selection list). This task is bound to the onpick event. It can be bound either with a conven- tional binding, or for simple tasks it can be specified with the onpick attribute on the tag itself. Attributes of the Element value (optional variable string) Gives a value to this , which is stored in the name variable of the , as detailed earlier. title (optional variable string) Gives a title to this , which some browsers may use to display the option, but some may ignore. onpick (optional variable URL) Provides a shorthand method of binding to the onpick event, for the com- mon case where the task is a simple go. Because this task is reduced to just the URL, it cannot contain any or elements, and its method is limited to GET. In complicated cases, put an element of type onpick inside the element. The Element WAP doesn’t define how the element is displayed. It has been imple- mented in many different ways, including using pulldown menus, scrolling lists, and lines of checkboxes on PDA-type devices and several different types of menus on cell phones. With a small screen, it isn’t always possible to display all the available options at the same time. There are several ways to get around this problem: if the options are displayed normally in the text of the page, as with checkboxes for example, then the normal facilities for scrolling the page will do. Many cell phones simply display the currently selected option; activating this for editing changes the screen to a different display with the options. When the editing is complete, the display changes back to the card. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  55. ,ch04.19703 Page 38 Wednesday, October 11, 2000 10:23 AM 38 Chapter 4: WML User Interaction The purpose of the element is to divide a long list of options into several sections. Different browsers may use this information in different ways: many simply ignore it (particularly those running on devices with large screens). Others may display the title of the group as part of the option display but not do anything more with it. Some may use the group title as the name of a submenu, with the contents of the group in that submenu. The information is a hint, nothing more. The element takes only one attribute: title (optional variable string) Specifies a title for this group, which may be used by the browser (for exam- ple, as the title of a submenu). It may also be completely ignored. As an example, the element can be used in the list of pizza toppings to separate the toppings into different groups: Pepperoni Ham Spicy Beef Anchovies Olives Mushrooms Chillies At publication time, few browsers support the element. The Element The and elements provide high-level user controls, but some- times all you want is a simple button or menu item. In these cases, the ele- ment is exactly what you need. A element is simply a way to specify some arbitrary type of control for the browser to make available to the user. This can be rendered as a graphical button (as many PDA browsers do), as an item in a menu (as most cell phone browsers do), or as just about anything the user can know about and interact with. This can even include things such as voice commands for a hands-off WAP browser (in a car, for example). A element contains nothing but the task to be performed when the element is activated. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.
  56. ,ch04.19703 Page 39 Wednesday, October 11, 2000 10:23 AM The Element 39 Attributes of the Element type (required string) Specifies the type of this element. This serves as a hint to the browser about the action this element triggers and may influence how the browser chooses to present the element. The following values are defined (undefined or unrecognized types are treated as if they had been specified as unknown): accept Acceptance of something. cell phones often bind this to the “yes” key if there is only one of this type in the card. prev Navigation backwards in the history stack (a task or something similar). help Request for some sort of help. The help provided can be context-sensitive. reset An operation that clears or resets the state of the interaction; for example, a “clear and start over” operation on a group of text fields or an opera- tion to deselect all options in a element. options A context-sensitive request for additional options; for example, a button to bring up an “advanced options” menu. delete Delete a single item or choice. To delete all items, use the reset type instead. unknown (or empty string) A generic element that doesn’t fit any existing category. Any name starting with X- or x- Experimental types. The exact behavior of these is undefined. Some browsers may implement some of these for development purposes. These types shouldn’t be used in production systems. Any name starting with vnd. (case-insensitive) Vendor-specific types. Some browsers may implement specific types of this form. Using these types allows you to enhance your WML for a specific browser, while remaining portable to others (unrecognized types are treated as if they were specified unknown). label (optional variable string) Specifies an optional text label for the element. For example, a browser that displays elements as graphical buttons can use this as the button’s text. This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright â 2000 O’Reilly & Associates, Inc. All rights reserved.