NN 2, IE 3
You want to use scripts to assemble the content of a page that replaces the current page.
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:
<l> <head> <title>Welcome Page</title> <script type="text/javascript"> // create custom page and replace current document with it function rewritePage(form) { // accumulate HTML content for new page var newPage = "<l><head><title>Page for "; newPage += form.entry.value; newPage += "</title></head><body bgcolor='#ffffcc'>"; newPage += "<h1>Hello, " + form.entry.value + "!</h1>"; newPage += "</body><l>"; // write it in one blast document.write(newPage); // close writing stream document.close( ); } </script> <body> <h1>Welcome!</h1> <hr> <form onsubmit="return false;"> <p>Enter your name here: <input type="text" name="entry" id="entry"></p> <input type="button" value="New Custom Page" onclick="rewritePage(this.form);"> </form> </body> <l>
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 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:
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.
Recipe 1.1 for combining string segments into one string.
script statement here<\/scr' + 'ipt>';
14.2.4 See Also