|[ Team LiB ]|
14.2 Creating New Page Content Dynamically
NN 2, IE 3
The following code gathers user-supplied text from a form on one page to provide some of the content for an entirely new page that replaces the first page:
Because one swipe of the document.write( ) method invoked on a loaded page erases the current page, the technique is to assemble the replacement HTML as a single string value and then invoke document.write( ) just once, passing the string as the parameter. Bear in mind that you are supplying text for the entire page, so any content that you might typically put into a page's head section (such as the document title) goes into the string. If you fail to provide tags for the html, head, and body elements, the browser treats the written string as the body content of the new page, automatically inserting the html, head, and body elements around your content. But it is better practice to supply those parts of the page yourself.
You can put any well-formed HTML and script content into the string that gets written to the new page. Thus, you can pass along script variables and their numeric or string values within written script tags. For example, if you wanted to pass the value of string variable myName from the current document to the next, the following HTML string accumulation statement puts the correct value in place. Notice how explicit quote marks are placed around the evaluated value, just as you'd do in a regular script statement involving a string:
htmlString += "var myName = '" + fred + "';";
Using document.write( ) for script tags, however, can be tricky in earlier browsers because the </script> tag that you assemble into the string may be interpreted as an end to the script that is assembling the text. To avoid this problem, break up the end-script tag and escape the forward slash, as follows:
It is vital that you follow the document.write( ) statement with a call to document.close( ). Even though the original page's script is blown away by the document.write( ), the document.close( ) method call still executes. If you don't include document.close( ), not all of the content of the string written to the next page may render. This is especially true if the content contains images or other external content.
14.2.4 See Also
Recipe 1.1 for combining string segments into one string.
|[ Team LiB ]|