The LiveWire server extension generates HTML dynamically; this HTML (which may also include client-side JavaScript statements) is then sent by the server over the network to the Navigator client, which displays the results. This process is illustrated in the following figure.
For more information on LiveWire, see the LiveWire Developer's Guide.In contrast to standard CGI programs, LiveWire JavaScript is integrated directly into HTML pages, facilitating rapid development and easy maintenance. LiveWire JavaScript contains an object framework that you can use to maintain data that persist across client requests, multiple clients, and multiple applications. LiveWire JavaScript also provides objects and methods for database access that serve as an interface to Structured Query Language (SQL) database servers.
Different versions of JavaScript work with specific versions of Navigator. For example, JavaScript 1.1 is for Navigator 3.0. For information, see "Specifying the JavaScript version".
Java is an object-oriented programming language designed for fast execution and type safety. Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting Java bytecodes. Java's object-oriented model means that programs consist exclusively of classes and their methods. Java's class inheritance and strong typing generally require tightly coupled object hierarchies. These requirements make Java programming more complex than JavaScript authoring.
<SCRIPT>A document can have multiple SCRIPT tags, and each can enclose any number of JavaScript statements.
JavaScript statements...
</SCRIPT>
<SCRIPT LANGUAGE="JavaScriptVersion">JavaScriptVersion specifies one of the following to indicate which version of JavaScript your code is written for:
JavaScript statements...
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
specifies JavaScript for Navigator 2.0.
<SCRIPT LANGUAGE="JavaScript1.1">
specifies JavaScript for Navigator 3.0.
You can use the LANGUAGE attribute to write scripts that contain Navigator 3.0 features, and these scripts will not cause errors if run under Navigator 2.0. The following examples show some techniques for using the LANGUAGE attribute.
<SCRIPT LANGUAGE="JavaScript">
// Define 1.0-compatible functions such as doClick() here
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript1.1">
// Redefine those functions using 1.1 features
// Also define 1.1-only functions
</SCRIPT>
<FORM ...>Example 2. This example shows how to use two separate versions of a JavaScript document, one for JavaScript 1.0 and one for JavaScript 1.1. The default document that loads is for JavaScript 1.0. If the user is running Navigator 3.0, the replace method replaces the page.
<INPUT TYPE="button" onClick="doClick(this)" ...>
. . .
</FORM>
<SCRIPT LANGUAGE="JavaScript1.1">Example 3. This example shows how to test the navigator.userAgent property to determine whether the user is running Navigator 3.0. The code then conditionally executes 1.1 features.
// Replace this page in session history with the 1.1 version
location.replace("js1.1/mypage.html")
</SCRIPT>
[1.0-compatible page continues here...]
<SCRIPT LANGUAGE="JavaScript">Example 4. In many cases, you can test the differences between JavaScript 1.0 and 1.1 by comparing new properties (such as navigator.javaEnabled or window.focus) to null. In JavaScript 1.0 and 1.1, an undefined property compares equal to null, so the 1.1 function references will be non-null in Navigator 3.0.
if (navigator.userAgent.indexOf("3.0") != -1)
jsVersion = "1.1"
else
jsVersion = "1.0"
</SCRIPT>
[hereafter, test jsVersion == "1.1" before use of any 1.1 extensions]
if (navigator.javaEnabled != null && navigator.javaEnabled()) {
// must be 3.0 and Java is enabled, use LiveConnect here...
} else {
// 2.0, no Java connection
}
<SCRIPT>Since browsers typically ignore unknown tags, non-JavaScript-capable browsers will ignore the beginning and ending SCRIPT tags. All the script statements in between are enclosed in an HTML comment, so they are ignored too. Navigator properly interprets the SCRIPT tags and ignores the line in the script beginning with the double-slash (//).
<!-- Begin to hide script contents from old browsers.
JavaScript statements...
// End the hiding here. -->
</SCRIPT>
Although you are not required to use this technique, it is considered good etiquette so that your pages don't generate unformatted script statements for those not using Navigator 2.0 or later.
Note
For simplicity, some of the examples in this book do not hide scripts, because the examples are written specifically for Navigator 2.0.
That's all, folks.
This script displays the following in Navigator:
You may sometimes see a semicolon at the end of each line of JavaScript. In general, semicolons are optional and are required only if you want to put more than one statement on a single line. This is most useful in defining event handlers, which are discussed in "Scripting event handlers".
<HEAD>This attribute is especially useful for sharing functions among many different pages.
<TITLE>My Page</TITLE>
<SCRIPT SRC="common.js">
...
</SCRIPT>
</HEAD>
<BODY>
...
The closing </SCRIPT> tag is required.
document.write("Included JS file not found")The SRC attribute can specify any URL, relative or absolute. For example:
<SCRIPT SRC="http://home.netscape.com/functions/jsfuncs.js">External JavaScript files cannot contain any HTML tags: they must contain only JavaScript statements and function definitions.
External JavaScript files should have the file name suffix .js
, and the server must map the .js
suffix to the MIME type "application/x-javascript", which the server sends back in the HTTP header. To map the suffix to the MIME type, add the following line to the mime.types
file in the server's config directory, and then restart the server.
type=application/x-javascript exts=jsIf the server does not map the
.js
filename suffix to "application/x-javascript" MIME type, Navigator will not load the JavaScript file specified by the SRC attribute properly.Note
This requirement does not apply if you are using local files.
You may already be familiar with HTML character entities by which you can define characters with special numerical codes or names by preceding the name with an ampersand (&) and terminating it with a semicolon (;). For example, you can include a greater-than symbol (>) with the character entity >
and a less-than symbol (<) with <
.
<HR WIDTH="&{barWidth};%" ALIGN="LEFT">So, for example, if barWidth were 50, this would create the following display:
As with other HTML, after layout has occurred, the display of a page can change only if you reload the page.
The following example shows a <NOSCRIPT> tag.
<NOSCRIPT>
<B>This page uses JavaScript, so you need to get Netscape Navigator 2.0
or later!
<BR>
<A HREF="http://home.netscape.com/comprod/mirror/index.html">
<IMG SRC="NSNow.gif"></A>
If you are using Navigator 2.0 or later, and you see this message,
you should enable JavaScript by choosing Network Preferences from
the Options menu.
</NOSCRIPT>
...
For a complete description of defining and calling functions, see "Functions".Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure--a set of statements that performs a specific task. A function definition has these basic parts:
Event handlers are introduced in "Scripting event handlers".Generally, you should define the functions for a page in the HEAD portion of a document. That way, all functions are defined before any content is displayed. Otherwise, the user might perform an action while the page is still loading that triggers an event handler and calls an undefined function, leading to an error.
The following example defines a simple function in the HEAD of a document and then calls it in the BODY of the document:
<HEAD>The function square takes one argument, called number. The function consists of one statement
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide script from old browsers
function square(number) {
return number * number
}
// End script hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT>
document.write("The function returned ", square(5), ".")
</SCRIPT>
<P> All done.
</BODY>
return number * number
that indicates to return the argument of the function multiplied by itself. The return statement specifies the value returned by the function. In the BODY of the document, the statementsquare(5)calls the function with an argument of five. The function executes its statements and returns the value twenty-five. The script displays the following results:
The square function used the line
document.write(...)
to display output in Navigator. This line calls the write method of the Navigator document object with JavaScript's standard object notation:objectName.methodName(arguments...)where objectName is the name of the object, methodName is the name of the method, and arguments is a list of arguments to the method, separated by commas.
In addition to defining functions as described here, you can also define Function objects, as described in "Function object".
A method is a function associated with an object. You'll learn more about objects and methods in Chapter 8, "Object model." But right now, we will explore write a little more, because it is particularly useful.
The write method takes any number of string arguments that can be string literals or variables. You can also use the string concatenation operator (+) to create one string from several when using write.
Consider the following script, which generates dynamic HTML with Navigator JavaScript:
<HEAD> <SCRIPT>The HEAD of this document defines two functions:
<!--- Hide script from old browsers
// This function displays a horizontal bar of specified width
function bar(widthPct) {
document.write("<HR ALIGN='left' WIDTH=" + widthPct + "%>")
}
// This function displays a heading of specified level and some text
function output(headLevel, headText, text) {
document.write("<H", headLevel, ">", headText, "</H",
headLevel, "><P>", text)
}
// end script hiding from old browsers -->
</SCRIPT> </HEAD>
<BODY>
<SCRIPT>
<!--- hide script from old browsers
bar(25)
output(2, "JavaScript Rules!", "Using JavaScript is easy...")
// end script hiding from old browsers -->
</SCRIPT>
<P> This is some standard HTML, unlike the above that is generated.
</BODY>
The following line creates the output of the bar function:
document.write("<HR ALIGN='left' WIDTH=", widthPct, "%>")Notice that the definition of bar uses single quotation marks inside double quotation marks. You must do this whenever you want to indicate a quoted string inside a string literal. Then the call to bar with an argument of twenty-five produces output equivalent to the following HTML:
<HR ALIGN="left" WIDTH=25%>write has a companion method, writeln, which adds a newline sequence (a carriage return or a carriage return and linefeed, depending on the platform) at the end of its output. Because HTML generally ignores newlines, there is no difference between write and writeln except inside tags such as PRE, which respect carriage returns.
To view HTML code that was generated with JavaScript write and writeln methods, the user must specify the view-source: protocol. If the user chooses Document Source or Frame Source from the View menu, the content displayed is that of the wysiwyg: URL. The following example shows a view-source: URL:
view-source:wysiwyg://0/file:/c|/temp/genhtml.htmlNavigator 2.0, does not print output created with JavaScript. For example, if the user chooses Print from the File menu to print the page in the previous example, you see only the line that reads "This is some standard HTML...," even though you see both lines onscreen.
Each event is recognized by certain objects (HTML tags), summarized in the following table:
<TAG eventHandler="JavaScript Code">where TAG is an HTML tag and eventHandler is the name of the event handler.
For example, suppose you have created a JavaScript function called compute. You can cause Navigator to perform this function when the user clicks a button by assigning the function call to the button's onClick event handler:
<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">You can put any JavaScript statements inside the quotation marks following onClick. These statements are executed when the user clicks the button. If you want to include more than one statement, separate statements with a semicolon (;).
Notice in the preceding example this.form
refers to the current form. The keyword this refers to the current object, which is the button. The construct this.form
then refers to the form containing the button. The onClick event handler is a call to the compute function, with the current form as the argument.
In general, it is good practice to define functions for your event handlers:
function bar(widthPct) {Here's another example:
document.write("<HR ALIGN='left' WIDTH=" + widthPct + "%>")
}
<INPUT TYPE="button" VALUE="Press Me" onClick="myfunc('astring')">Be sure to alternate double quotation marks with single quotation marks. Because event handlers in HTML must be enclosed in quotation marks, you must use single quotation marks to delimit string arguments. For example:
<FORM NAME="myform">
<INPUT TYPE="button" NAME="Button1" VALUE="Open Sesame!"
onClick="window.open('mydoc.html', 'newWin')">
</FORM>
<HEAD> <SCRIPT>The display in Navigator will look like this:
<!--- Hide script from old browsers
function compute(f) {
if (confirm("Are you sure?"))
f.result.value = eval(f.expr.value)
else
alert("Please come back again.")
}
// end hiding from old browsers -->
</SCRIPT> </HEAD>
<BODY>
<FORM>
Enter an expression:
<INPUT TYPE="text" NAME="expr" SIZE=15 >
<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">
<BR>
Result:
<INPUT TYPE="text" NAME="result" SIZE=15 >
</FORM>
</BODY>
The HEAD of the document defines a single function, compute, taking one argument, f, which is a Form object. The function uses the Navigator JavaScript method confirm to display a Confirm dialog box with OK and Cancel buttons.
If the user clicks Cancel, then confirm returns false and the alert method displays another message.
<SCRIPT LANGUAGE="JavaScript">Note that event handlers are function references, so you must assign
function fun1() {
...
}
function fun2() {
...
}
</SCRIPT>
<FORM NAME="myForm">
<INPUT TYPE="button" NAME="myButton"
onClick="fun1()">
</FORM>
<SCRIPT>
document.myForm.myButton.onclick=fun2
</SCRIPT>
fun2
, not fun2()
(the latter calls fun2 and has whatever type and value fun2 returns).
Also, since the event handler HTML attributes are literal function bodies, you cannot use <INPUT onClick=fun1>
in the HTML source to make fun1 the onClick handler for an input; you must call fun1 instead, as in the example.
One of the most important uses of JavaScript is to validate form input to server-based programs such as LiveWire applications or CGI programs. This is useful because
<HEAD>
<SCRIPT LANGUAGE="javascript">
function isaPosNum(s) {
return (parseInt(s) > 0)
}
function qty_check(item, min, max) {
var returnVal = false
if (!isaPosNum(item.value))
alert("Please enter a postive number" )
else if (parseInt(item.value) < min)
alert("Please enter a " + item.name + " greater than " + min)
else if (parseInt(item.value) > max)
alert("Please enter a " + item.name + " less than " + max)
else
returnVal = true
return returnVal
}
function validateAndSubmit(theform) {isaPosNum is a simple function that returns true if its argument is a positive number, and false otherwise.
if (qty_check(theform.quantity, 0, 999)) {
alert("Order has been Submitted")
return true
else {
alert("Sorry, Order Cannot Be Submitted!")
return false
}
}
</SCRIPT>
</HEAD>
qty_check takes three arguments: an object corresponding to the form element being validated (item) and the minimum and maximum allowable values for the item (min and max). It checks that the value of item is a number between min and max and displays an alert if it is not.
<BODY>This form submits the values to a page in a LiveWire application called
<FORM NAME="widget_order" ACTION="lwapp.html" METHOD="post">
How many widgets today?
<INPUT TYPE="text" NAME="quantity" onChange="qty_check(this, 0, 999)">
<BR>
<INPUT TYPE="button" VALUE="Enter Order" onClick="validateAndSubmit(this.form)">
</FORM>
</BODY>
lwapp.html
. It also could be used to submit the form to a CGI program.The onChange event handler is triggered when you change the value in the text field and move focus from the field by either pressing the Tab key or clicking the mouse outside the field. Notice that both event handlers use this to represent the current object: in the text field, it is used to pass the JavaScript object corresponding to the text field to qty_check, and in the button it is used to pass the JavaScript Form object to validateAndSubmit.
<INPUT TYPE="submit"When qty_check returns false if the data are invalid, the onSubmit handler will prohibit the form from being submitted.
onSubmit="return qty_check(theform.quantity, 0, 999)"