by Ramesh Chandak
Among all the Internet buzzwords you hear today, I am sure one of them has been Java. What is Java? Why is it so hot? What is all the hype about? Why is everyone saying Java has revolutionized the computer and information industry? Where did it come from? If Microsoft didn't make it, who did? All this and much more. Never before has the computing industry undergone such a transformation in so little time. First the Internet, then Netscape Navigator, and now Java! The Internet has completely changed the development and distribution paradigm.
Java is a product from JavaSoft, the software division of Sun Microsystems. With the advent of browser technology and Web authoring tools, creating and navigating the Web pages has become very easy. But these pages have been mostly static, with very little or no interactivity, as if they had no life of their own. They were straight rendering of text and graphics. Static pages generate very little interest for the surfer. There was a need for something that would liven up the experience of surfing the Internet. Then comes along Java!
What is Java? Java is an object-oriented programming language. Java is multithreaded, secure, and portable. It is based on C++, the object-oriented programming language that has been in use for several years now. You can create portable, interactive Web pages using Java. The Java Virtual Machine (JVM) is the core of the Java runtime system. It is a software-based microprocessor and translates Java executables into platform-specific instructions. Java code itself is machine-independent, but JVM is not. JVM is machine-specific. The Java compiler compiles your Java program into compiled bytecodes. A bytecode is a runtime form that executes on the JVM. The extra layer of JVM makes Java programs sluggish compared to native programs written in C or C++. Java applications are portable because of the JVM implementation but are comparatively slower. Just-In-Time (JIT) compilers have addressed this issue. A JIT compiler compiles the bytecodes into native code on-the-fly. It acts as the intermediate layer between the JVM and the target machine. A Java-enabled browser means the JVM is built into it. When the browser comes across the <APPLET> tag, it downloads and executes it using its built-in JVM.
Java and JavaScript are different. Java is an object-oriented programming language. JavaScript is an object-based scripting language. Using Java, you can build standalone applications and applets. Using JavaScript, you cannot build Java applications and applets. JavaScript, originally called LiveScript, is a technology from Netscape. Java is a technology from Sun Microsystems. JavaScript can be considered an extension to HTML. HTML is good for straight rendering of text and graphics, but lacks the capability to make the surfing experience interactive. There are certain things you cannot do using pure HTML-for example, validating user response. Using just HTML, you would have to use CGI scripts or programs at the server end to process and validate user responses and return the results to the browser. Using JavaScript, you can do this directly within HTML without having to send the data back and forth. This reduces network traffic and improves overall response. Only validated data is sent to the server. You can do much more with JavaScript. You can add animation to your Web pages. You can display alert windows and message boxes if the user does not enter the correct data or correct format of the data. Simply put, you can build interactive Web pages using HTML and JavaScript.
According to a recent ComputerWorld survey, there are approximately 3 million programmers around the world (and still growing!) who use Visual Basic as their primary programming language. On the other hand, there are approximately 1.1 million programmers who use C/C++ as their primary programming language. Those 3 million programmers would benefit from VBScript, Microsoft's scripting language for the Web. Because VBScript is a subset of Visual Basic, these programmers would find it easy to use. Most of all, VBScript would benefit the non-programmers, whose background is not strictly programming. Non-programmers who are interested in creating their own interactive Web pages would find it easy to program using VBScript since the programming structure is based on the BASIC language. The VBScript learning curve would be a lot shorter compared to JavaScript for a non-programmer.
It is important to understand that both JavaScript and VBScript have their advantages and disadvantages. Java is portable and object-oriented. VBScript is not truly object-oriented. Unless you are an expert in object-oriented and C++ programming, Java involves a steeper learning curve.
Scripting using VBScript and JavaScript is easier than programming in C and C++. Take a look at the HyperCard community for the Macintosh. The introduction of HyperCard and its scripting language, HyperScript, revolutionized the Macintosh world of programming. A whole new generation of applications has been developed by a variety of people-both programmers and non-programmers.
As of this writing, only Microsoft Internet Explorer 3.0 supports VBScript. In contrast, JavaScript is supported by Netscape Navigator 3.0, Microsoft Internet Explorer 3.0, and HotJava 1.0, Sun Microsystem's browser.
This chapter introduces Java and its features, as well as JavaScript and its programming syntax and structure. It also discusses Java applets and Java classes. It further discusses VBScript and its syntax and structure. After reading this chapter, you will have gained a good understanding of Java, JavaScript, and VBScript, and how they compare with each other. This chapter is not a programming reference guide on JavaScript and VBScript. It does not include all the programming structures and conventions available in these scripting languages. Instead, it discusses the main features of each language, including functions, subroutines, arithmetic, and logical and comparison operators, and compares and contrasts them. This chapter also discusses a Web page example written using both JavaScript and VBScript. By comparing both the scripts, you will gain a better insight into these languages.
Java is an object-oriented programming language. Java includes a runtime interpreter, an Application Programming Interface (API), and a set of development tools. Java is distributed as JDK-the Java Developer's Kit. As of this writing, the latest version of JDK is 1.1. You can download JDK from JavaSoft's Web site: http://java.sun.com. Figure 18.1 shows the JavaSoft home page.
Java is secure. Java is multithreaded. Java is derived from C/C++.
If you are an experienced C/C++ programmer, you will find it easy
to get started with Java. It includes the Java Application Programming
Interface-a library of methods for developing platform-independent,
distributed applications that include full networking and windowing
support.
NOTE |
If you are an experienced C++ programmer, you will appreciate Java and its features, including built-in networking, platform-independent API class library, and robust exception handling. When programming in Java, you no longer have to deal with pointers. Java understands object-oriented structure only. Everything you define and use in Java must be an object. |
Figure 18.2 shows the Java development framework. The Java source code utilizes the Java API and user-defined classes. The source code is compiled into Java runtime bytecode by the Java compiler. The runtime bytecode runs on the Java Virtual Machine (JVM), a software-based microprocessor. The JVM is an interpreter and can reside on any platform, including Windows 3.1, Windows 95, UNIX, Macintosh, and so on, thus making Java applications platform-independent.
The Java Developer's Kit contains a variety of tools and Java development information. Following is a list of the main components of the JDK:
The Java API includes class definitions and methods that provide links into the native windowing and networking capabilities of the host operating system. It is the common thread between Java programs and any host operating system. The Java runtime system and API make Java portable. The Java runtime system is not tied to any particular operating system. It has been developed from scratch. The Java API is a universal API for writing applications targeted at all operating systems.
Java is supported by both industry standard browsers-Netscape Navigator and Microsoft Internet Explorer. There are several applications that have been written using Java. HotJava, Sun Microsystem's Web browser, is written completely using Java. You can develop a variety of applications using Java. Using Java you can write multithreaded applications and secure, distributed, multiplatform applications. You can also write object-oriented Web applications. You can write applets using Java. An applet is not a standalone application; it cannot run on its own. A browser or an applet viewer needs to be used to run an applet. When the browser encounters the <APPLET> tag, it downloads the applet and the JVM embedded within the browser executes it.
Figure 18.3 describes the Java API structure. The Java API consists of two types of packages: packages that are built-in and packages that a Java programmer can define and use.
A Java package is a group of related interfaces, classes, and exceptions. The grouping is done simply for ease of understanding and convenience. See Figure 18.4.
Figure 18.4 : A Java package includes interfaces, classes, and exceptions.
Java is object-oriented. Anything you define and use must be an object. A class is the basic object-oriented component in Java. An interface is a collection of related methods. An exception is an event that alters the normal course of program execution.
Class: A class is the basic object-oriented component in Java. It includes methods and variables. Variables store data. Methods are functions that operate on the classes and variables. For example, the checkbox class in the java.awt package is used to implement checkbox and radio button GUI controls in Java applications. The file class in the java.io package is used to provide system-independent access to a file or a directory on the host operating system. The applet class in the java.applet package is used to implement Java applets.
Interface: An interface is a collection of related methods. For example, the imageproducer is a set of functions for classes that produce images. The imageproducer methods are used to reconstruct or modify an image being produced.
Exception: An exception is an event that alters the normal course of program execution.
The Java Developer's Kit comes with a number of examples. Figure 18.5 shows a tic-tac-toe example, written as a Java applet and executed using Microsoft Internet Explorer.
The file tictactoe.java on the enclosed CD-ROM includes the source code for the tic-tac-toe Java applet.
A Java-enabled browser means the Java runtime interpreter and Java Virtual Machine are integrated within the browser. Applets are Java programs that are linked to the Web browser. An applet may be used to enhance a Web document by displaying animation or playing sound. It cannot modify the state of the HTML document being displayed. It is executed by the Java runtime interpreter that is integrated with the browser.
An applet is specified by the <applet>... </applet> tags within the HTML code. When the browser encounters the <applet> tag, it downloads the applet, runs a number of security tests on it and passes it to the runtime interpreter and Java Virtual Machine that execute it locally. Applets are executed within a well-defined area of the browser. It is similar to running a command-line program. The browser does not execute the applet. The runtime interpreter executes the applet. You can think of the runtime interpreter as a plug-in or helper application to the browser.
Java and JavaScript are not the same. Nor are they competitors to each other. Java is an object-oriented programming language. JavaScript is a scripting language. You can use Java to write object-oriented, network, distributed, secure, multithreaded Java applications. The source code files have .java extensions. Java source code is compiled and stored in .class files. See Figure 18.6.
JavaScript is embedded within your HTML code. It is an extension
to your HTML code. You can change the appearance and behavior
of your Web pages dynamically using JavaScript. You can process
mouse events such as mouse click or the mouse moving over a certain
part of the Web page and initiate certain actions on such events.
For example, you can display different background bitmaps, depending
on the day of the week. You can process form data when the user
clicks the submit button and alert the user of any invalid data.
Java supports static binding. When writing code using Java, you
must declare the types of variables before you can use them. JavaScript
supports dynamic binding. With JavaScript it is not necessary
to declare the type. If you do not declare the type of the variable,
JavaScript interprets it at runtime, based on the context in which
it is used. For example, if a variable is used to perform addition
of numbers, it is interpreted as a number. If a variable is used
to perform string concatenation, it is interpreted as a string.
Such loose binding makes JavaScript lightweight and portable.
Similarly, if you declare functions in JavaScript, it is not necessary
to specify the type of the return value of the function. On the
other hand, you must declare the type of the return value of the
function in Java. Java applets can also be executed using any
of the three browsers. Java is available as JDK from JavaSoft's
Web site. If you download and install Netscape Navigator, Microsoft
Internet Explorer, or HotJava, you have basically everything you
need to use JavaScript.
NOTE |
You can use Java to develop non-Web-based applications. Since JavaScript and VBScript are extensions to HTML, they are used primarily to create Web applications. However, VBScript can be used as a component in other Windows applications. |
Listing 18.1 shows a HelloWorld program written in Java.
Listing 18.1. A HelloWorld program written in Java.
import java.lang.System; class HelloWorld { public static void main (String args[]) { System.out.println("Hello World!"); } }
Compare the preceding Java code to JavaScript and VBScript code for writing the same HelloWorld program. Listing 18.3 shows an example of a HelloWorld program written in JavaScript.
The Java API includes the following packages. A Java package includes
interface, classes, and exceptions.
java.net: | A library of classes and methods for implementing socket-based client/server networking |
java.io: | A library of classes and methods for stream-based I/O |
java.applet: | A library of classes and interfaces for applet development |
java.awt: | A library of windowing classes and methods called Abstract Windowing Toolkit (AWT) |
java.awt.image: | A library of classes for managing image data, including color models, cropping, and color filtering |
java.awt.peer: | A library of interface definitions that map platform-independent AWT classes to their native platform-dependent implementations; it does not include any classes |
java.lang: | A library of methods and classes for applet, console, and window programming |
java.util: | A library of Java utilities |
sun.tools.debug: | A library of debugging tools and utilities |
NOTE |
To keep abreast of the latest on Java, visit Javasoft's home page regularly. |
JavaScript is an object-based scripting language. Even though
it is object-based, JavaScript does not support inheritance. You
can define your own objects in JavaScript and use them together
with JavaScript's built-in objects to write Web pages. As of this
writing, there are a total of 17 JavaScript objects. Table 18.1
lists them.
Object | Meaning |
navigator | Base class for all HTML objects |
window | Base class for the document object |
document | Contains information about all HTML properties inside the current page |
history | Contains browser's URL history list |
form | Contains information about the defined form |
date | Contains date information, including system date function |
math | Includes math constants and functions |
string | Contains information about string functions |
radio | Contains information about a form's radio button |
checkbox | Contains information about a form's checkbox button |
select | Represents a form's list as an array |
button | Contains information about a form's button; it could represent a form's reset, submit, or custom button |
text, textarea | Contains information about a form's text box |
location | Contains information about the current URL location |
Listing 18.2 shows an example of HTML code that includes a JavaScript function. The JavaScript code is identified by the <SCRIPT> tag. The code is embedded between the beginning and ending <SCRIPT> tags.
Listing 18.2. Basic structure of a JavaScript function.
<SCRIPT LANGUAGE="JavaScript"> <!-- function <function_name> { ... } // --> </SCRIPT>
Listing 18.3 shows a JavaScript-based HelloWorld function.
Listing 18.3. JavaScript HelloWorld function.
<SCRIPT LANGUAGE="JavaScript"> <!-- function HelloWorld() { alert("Hello World!"); } // --> </SCRIPT>
The LANGUAGE attribute indicates the scripting language
that is used. The browser interprets the code accordingly. Microsoft
Internet Explorer 3.0 can interpret both JavaScript and VBScript.
Netscape Navigator and HotJava can interpret only JavaScript.
NOTE |
Although currently only Microsoft Internet Explorer supports VBScript, other browsers are expected to include support for interpreting VBScript code. |
JavaScript functions can be placed anywhere inside the HTML code, including the HEAD and BODY sections. It is recommended you place all your functions and procedures in one location, usually toward the end of the BODY section, before the </BODY> tag.
JavaScript operators include arithmetic, comparison, logical,
and bit operators. Table 18.2 shows the JavaScript arithmetic
operators.
Meaning | |
Addition | |
Subtraction/negation | |
Multiplication | |
Division | |
Increment | |
Decrement | |
Modulus |
Table 18.3 shows the JavaScript comparison operators.
Meaning | |
Non-equality | |
Greater than | |
Greater than or equal to | |
Less than | |
Less than or equal to |
Table 18.4 shows the JavaScript logical operators.
Meaning | |
Logical AND | |
Logical OR | |
Logical NOT |
Table 18.5 shows the JavaScript bit operators.
Meaning | |
Bitwise AND | |
Bitwise OR | |
Bitwise XOR |
A single = is the assignment operator. It is used to store a value into a variable.
Table 18.6 shows the JavaScript flow of control statements.
Statement | Meaning |
For ([initial_expression;][condition;][increment_expression]) { statement 1 ... statement N } | Execute the code within the loop for N times where N is specified in the For loop |
For Each...Next | Execute the code within the loop for each item in the specified collection |
If (condition) { statement 1... statement N} [else { statement 2}] | If...Else statement |
while (condition) { statement 1 ... statement N } | Execute the code within the loop as long as the specified condition is true |
VBScript is a lightweight portable subset of Visual Basic, the language, and Visual Basic for Applications, the scripting language used in Microsoft Excel and Word. It is a scripting language that can be used as part of your HTML code for designing and modifying Web pages. Similar to JavaScript, you can change the appearance and behavior of your Web pages dynamically using VBScript. You can process mouse events such as a mouse click or the mouse moving over a certain part of the Web page and initiate certain actions on such events. For instance, you can display different background bitmaps, depending on the day of the week. You can process form data when the user clicks the Submit button and alert the user of any invalid data. VBScript can also be used as part of other applications that use ActiveX controls, OLE Automation servers, and Java applets. As of this writing, VBScript is available only as part of Microsoft Internet Explorer 3.0.
If you are already familiar with Visual Basic, the programming language, you will be able to quickly and easily grasp VBScript. There are a few important differences, though. VBScript does not support strict data types. It supports only variants. It does not support file I/O. Nor does it include direct access to the underlying operating system.
How does VBScript compare with JavaScript? Well, it is directly
comparable to JavaScript. In fact, VBScript is a competitor to
JavaScript. Both languages have their advantages and disadvantages.
Visual Basic has been around for quite some time. Java is relatively
new. According to a recent ComputerWorld survey, there are approximately
3 million programmers who use Visual Basic as their primary programming
language. The introduction of VBScript is clearly a welcome sign
for these programmers. A lot of them would find it easier to use
VBScript with their HTML code than to learn a new language, JavaScript.
Neither JavaScript nor VBScript can produce standalone applets.
However, they can be used to add intelligence and interactivity
to HTML documents.
NOTE |
If you are an experienced Visual Basic programmer you will find it easy to learn and understand the lightweight subset of Visual Basic, VBScript. |
Presently, VBScript is available for Windows 95, Windows NT, Windows 3.1, and Power Macintosh platforms. UNIX versions of VBScript for Sun, HP, Digital, and IBM platforms are under development. VBScript can be used with HTML code with or without ActiveX controls.
Using JavaScript and VBScript with your HTML code reduces Internet
traffic. You can perform data validation on the client side instead
of sending the data over to the server to be processed by CGI
scripts. Only valid data is transmitted over the Net. This is
similar to a client/server environment using PowerBuilder or Visual
Basic and Sybase where the data validation is performed by the
GUI front end and Sybase receives only validated data to work
with.
NOTE |
CGI allows Web browsers to interact with the server programs. You can use CGI and other similar technologies, including ISAPI, NSAPI, OLE, and IDC, to perform tasks such as querying the database. For more on CGI, see Chapter 20, "CGI and VBScript." |
Listing 18.4 shows HTML code that includes a VBScript function. The VBScript code is identified by the <SCRIPT> tag. It is embedded between the beginning and ending <SCRIPT> tags.
Listing 18.4. VBScript function.
<SCRIPT LANGUAGE="VBScript"> <!-- Function End Function --> </SCRIPT>
Listing 18.5 shows HTML code that includes a VBScript subroutine. If you know Visual Basic, you realize that VBScript coding is very similar because it is a subset of Visual Basic.
Listing 18.5. VBScript HelloWorld function.
<SCRIPT LANGUAGE="VBScript"> <!-- Sub HelloWorld Msgbox "Hello World!" End Sub --> </SCRIPT>
VBScript supports procedures or subroutines just as Visual Basic does. Subroutines are defined in VBScript using the sub keyword. Use the Call statement to initiate a call to the VBScript subroutine. Listing 18.6 shows a Call statement to the HelloWorld subroutine declared in Listing 18.5.
Listing 18.6. Calling a VBScript subroutine.
<SCRIPT LANGUAGE="VBScript"> <!-- Call HelloWorld Sub HelloWorld Msgbox "Hello World!" End Sub --> </SCRIPT>
Listing 18.7 demonstrates the use of comments inside your VBScript code.
Listing 18.7. Use of comments in VBScript.
<SCRIPT LANGUAGE="VBScript"> <!-- 'Call the HelloWorld subroutine 'this is the commented line Call HelloWorld Sub HelloWorld Msgbox "Hello World!" End Sub --> </SCRIPT>
Not all browsers support VBScript. Therefore, the VBScript functions and procedures are embedded within the comment tags (<!-- and -->). Any browser that does not interpret VBScript can bypass the VBScript functions and procedures without displaying the code.
VBScript functions and procedures can be placed anywhere inside
the HTML code, including the HEAD and BODY sections.
It is recommended you place all your functions and procedures
in one location, usually toward the end of the BODY section
before the </BODY> tag, similar to JavaScript coding.
NOTE |
VBScript can be used to control and integrate both HTML intrinsic controls and ActiveX controls. |
VBScript supports arrays and collections of variables, similar to Visual Basic.
VBScript operators include arithmetic, comparison, and logical
operators. Table 18.7 shows the VBScript arithmetic operators.
Meaning | |
Addition | |
Subtraction/negation | |
Multiplication | |
Division | |
Integer division | |
String concatenation | |
Exponentiation | |
Remainder on division |
Table 18.8 shows the VBScript comparison operators.
Meaning | |
Equality | |
Non-equality | |
Greater than | |
Greater than or equal to | |
Less than | |
Less than or equal to | |
Object equivalence |
Table 18.9 shows the VBScript logical operators.
Meaning | |
Logical AND | |
Logical OR | |
Logical NOT | |
Logical exclusion | |
Logical equivalence | |
Logical implication |
The VBScript error object Err is built into it. It can be used to track runtime errors. It has several properties that can be used to track and handle runtime errors.
The only data type VBScript supports is a variant. It is a one for all data type. A single data type makes the language lightweight and portable. It also makes it easier and faster to download.
A variant is a special kind of data type that can contain different kinds of information, depending on the context in which it is used. If it is used in numeric context, a variant data type contains numeric data. If it is used in string context, a variant data type contains string data.
Table 18.10 shows the VBScript variant data types.
Data Type | Meaning |
integer | Integer value between -32,768 and 32,767. |
Long integer | Integer in the range -2,147,483,648 to 2,147,483,648. |
Double | Double-precision, floating-point number. The range for negative values is -1.7976931348232E308 to -4.940656458412E-324. The range for positive values is 4.940656458412347E-324 to .79769313486232E308. |
single | Single precision floating-point number. The range for negative values is -3.402823E38 to -.1401298E-45. The range for positive values is 1.401298E-45 to 3.402823E38. |
date | Date. |
Empty | If it represents a number, its value is 0. If it represents a string, its value is "". |
string | Variable length string; it can hold up to 2 billion characters in length. |
Null | Contains no valid data. |
Boolean | True or false. |
Byte | Integer range: 0-255. |
Object | Object. |
Error | Error number. |
You can use the function vartype to return information about the type of data stored in a variant.
You can define constants in your VBScript code using the DIM statement. Listing 18.8 shows an example of declaring a constant MyString. The assignment statement determines the data type of the constant. In this case the variant MyString is of type string.
Listing 18.8. Assign a string to a variant.
Dim MyString MyString = "This is my string".
If you assign a number, MyString represents a numeric data type. Listing 18.9 shows an example of assigning a number to a variant.
Listing 18.9. Assign a number to a variant.
Dim MyString MyString = 786
If you assign a number as a quoted string, MyString represents a string data type. Listing 18.10 shows an example of assigning a number as a quoted string to a variant.
Listing 18.10. Assign a number as a quoted string to a variant.
Dim MyString MyString = "786"
Date and Time literals are represented by enclosing them within # signs. Listing 18.11 shows an example of assigning a date to a variant.
Listing 18.11. Assign a date to a variant.
Dim DepartureDate DepartureDate = #08-23-96#
Table 18.11 shows the VBScript flow of control statements.
Statement | Meaning |
For.Next | Execute the code within the loop for N times, where N is specified in the For loop. |
For Each.Next | Execute the code within the loop once for each item in the specified collection. |
If.Then | Simple If.Then statement. |
If.Then.Else.End If | The standard If.Then.Else.End If statement. |
Select | Select Case test expression.
Case Case End Select |
Do.Loop | Execute the code within the loop as long as the loop expression is true. |
While.Wend | Execute the code within the loop as long as the specified condition is true. |
VBScript supports functions just like Visual Basic does. Functions are defined in VBScript using the Function keyword. Similar to variables, VBScript functions are also loosely typed. You need not explicitly define the type of return value of a function. The type of return value is automatically set, based on the context in which it is used.
VBScript supports procedures just as Visual Basic does. Procedures are defined in VBScript using the sub keyword. JavaScript does not support procedures.
VBScript can integrate both HTML intrinsic and ActiveX controls
easily. As of this writing, JavaScript does not support integration
of ActiveX controls.
NOTE |
Microsoft's ActiveX Control Pad offers a visual editing environment that lets you develop Web pages interactively. You can also integrate ActiveX and other HTML intrinsic controls easily using ActiveX Control Pad. |
This section discusses the importance of having a set of standards and conventions when programming using JavaScript and VBScript. It outlines the advantages of using coding guidelines. It recommends the approach that best suits your company. This section is not intended to be a reference guide on the coding standards for JavaScript and VBScript. However, it recommends a list of steps that you should consider when establishing the standards and conventions for your company.
If your company does not have a coding convention, you should seriously consider establishing one. Establishing and using corporate-wide scripting standards and conventions is critical to the long-term success of any mission-critical project involving JavaScript and VBScript. Coding guidelines encourage reusability and improve project maintenance. They improve team communication and the debugging process. In this fast-changing world, developers move from one project to another. A set of standards and conventions helps make such moves easy. If a developer starts working on a project that has already been in the works for quite some time, being familiar with the coding standards and conventions from the previous project reduces the learning curve involved with the new project.
Typically the norm is to continue with your established coding conventions and adapt them to JavaScript and VBScript. For example, if you have been using 4GL tools such as Visual Basic and PowerBuilder for client/server application development and have been following certain guidelines when writing applications using such tools, it makes sense to adopt such guidelines and modify them as necessary for JavaScript and VBScript scripting. This approach maintains as much uniformity as possible across coding guidelines using different tools and languages.
An interesting twist to using JavaScript and VBScript is the ability
to share your code worldwide. Any Web page designed and placed
on the Internet is accessible to developers and programmers worldwide,
along with its source code. Although there is no official worldwide
set of standards and conventions, those set forth by JavaSoft
and Microsoft can be considered as the worldwide set of standards
and conventions.
NOTE |
Microsoft's suggested standards and conventions for VBScript are available for download at http://www.microsoft.com/vbscript. JavaSoft's suggested standards and conventions for JavaScript are available for download at http://home.netscape.com/comprod/products/navigator /version_2.0/script/index.html. |
Establishing a set of standards and conventions includes, but is not limited to, the following steps:
Table 18.12 summarizes the different features of Java, JavaScript,
and VBScript.
Java | JavaScript | VBScript |
Programming language | Scripting language | Scripting language |
Object-oriented | Object-based | Not object-based |
Strongly typed | Loosely typed | Loosely typed |
No support for functions | Supports functions | Supports functions |
Interacts with browser as applet | Supports functions | Extension to HTML |
Secure | Secure | Secure |
Derived from C/C++ | C/C++ based | Subset of Visual Basic |
Supported by all three browsers | Supported by all three browsers | Presently supported by only Internet Explorer |
Steeper learning curve if not familiar with C/C++ | Easy to learn | Based on BASIC |
In this section, we'll review and analyze a VBScript example downloaded from the Web site http://www.microsoft.com/vbscript. We will also review and analyze the JavaScript code for the same example. Figure 18.7 shows a simple Web page created by the HTML code included in the file msftd.html on the companion CD-ROM. This HTML displays an order form that lets you place orders for flowers. You specify the occasion and enter the name and address where the flowers should be sent.
Figure 18.7 : An ordering flowers Web page created using HTML and VBScript.
Let us look at the code part by part. Listing 18.12 is all HTML code that is used to set up the form. Three radio buttons are displayed to let the user select from Birthday (default), Anniversary, and Get Well Soon occasions. These buttons are displayed using the <Input Type> tag.
Next, the data entry fields for entering the name and address of the destination are added. The <Input> tag is used to add these fields. Three buttons, Submit, Clear, and Init, are added at the bottom. The Submit button sends the order. The Clear button clears the name and address fields. The Init button initializes the data entry fields.
Listing 18.12. HTML code for setting up the form for ordering flowers.
<HEAD><TITLE>VBScript sample: Ordering Flowers</TITLE></HEAD> <BODY> <TABLE WIDTH="80%"> <TR VALIGN=bottom> <TD WIDTH="40%"><IMG SRC="/vbscript/us/vbssamp/msftd/msftd.gif" ALIGN=center></TD> <TD WIDTH="60%"><FONT SIZE=12><I>Order Flowers</I></FONT></TD> </TR> </TABLE> <FONT FACE="Times New Roman" SIZE=4>What is the occasion?</FONT><BR> <PRE> <INPUT TYPE=RADIO NAME=OptOccasion CHECKED> Birthday <INPUT TYPE=RADIO NAME=OptOccasion> Anniversary <INPUT TYPE=RADIO NAME=OptOccasion> Get well soon </PRE> <FONT FACE="Times New Roman" SIZE=4>When and where should the flowers be sent?</FONT><BR> <PRE> Date <INPUT NAME=TxtDate SIZE=60> Name <INPUT NAME=TxtName SIZE=60> Address <INPUT NAME=TxtAddress SIZE=60> City <INPUT NAME=TxtCity SIZE=60> State <INPUT NAME=TxtState SIZE=60> Zip code <INPUT NAME=TxtZip SIZE=60> <INPUT TYPE=BUTTON VALUE="Submit" NAME="BtnSubmit"> <INPUT TYPE=BUTTON VALUE="Clear" NAME="BtnClear"> <INPUT TYPE=BUTTON VALUE="Init" NAME= "BtnInit"><BR></PRE>
Listing 18.13 shows the VBScript code that is used to process the data entered by the user. It is also used to process the mouse click events when the user clicks the Submit, Clear, or Init button. Before the days of JavaScript and VBScript, such processing would be done on the server, using CGI programs and scripts. VBScript extends the HTML code and validates user input before it is sent to the server. This reduces network traffic and improves the overall performance of your Web page.
There are two variants declared: strMsgBoxTitle and bValidOrder. Note that the types of these variables have not been defined. One can guess from the names of the variables that strMsgBoxTitle is likely to store string data and bValidOrder is expected to store a Boolean value that is true or false.
There are six procedures defined in this VBScript code: Window_OnLoad, BtnInit_OnClick, BtnSubmit_OnClick, ValidateDeliveryDate, CheckSpecified, and BtnClear_OnClick.
The subroutine Window_OnLoad is executed when the Web page window is first loaded by the browser. It assigns the value MSFID to the variant strMsgBoxTitle. The variant StrMsgBoxTitle is assigned a string value and therefore it is now a string variable. The strMsgBoxTitle is used to display the title for the message box. Next, the subroutine Window_OnLoad calls the BtnInit_OnClick procedure. This procedure initializes the data entry fields.
The procedure BtnInit_OnClick initializes the data entry fields. It is executed when the Web page window is first loaded. It is also executed when the user clicks the Init button.
The procedure BtnSubmit_OnClick is executed when the user clicks the Submit button. It checks whether the data entered is valid. If it is valid, the variable bValidOrder that is initialized to true at the beginning of this procedure retains its initialized value. If bValidOrder is true, the order is sent. If the data entered is not valid, bValidOrder is set to false and the control is returned to the user on the Web page.
The procedure ValidDeliveryDate checks whether the value specified in the date field is valid.
The procedure CheckSpecified is actually called by the BtnSubmit_OnClick procedure. It checks whether the data entered in name and address fields is valid.
The procedure BtnClear_OnClick is executed when the user clicks the Clear button. It clears the data entry fields.
Listing 18.13. VBScript code.
<SCRIPT LANGUAGE="VBScript"> <!-- Option Explicit Dim strMsgBoxTitle Dim bValidOrder Sub Window_OnLoad strMsgBoxTitle = "MSFTD" Call BtnInit_OnClick End Sub Sub BtnInit_OnClick TxtName.Value = "Joe Smith" TxtAddress.Value = "1 Main Street" TxtCity.Value = "Springfield" TxtState.Value = "Washington" TxtZip.Value = "12345" TxtDate.Value = Date + 3 End Sub Sub BtnSubmit_OnClick bValidOrder = True Call CheckSpecified(txtName.Value, "Please specify a name.") Call CheckSpecified(txtAddress.Value, "Please specify an address.") Call CheckSpecified(txtCity.Value, "Please specify a city.") Call CheckSpecified(txtState.Value, "Please specify a state.") Call CheckSpecified(txtZip.Value, "Please specify a zip code.") Call CheckSpecified(txtDate.Value, "Please specify a date.") Call ValidateDeliveryDate If bValidOrder Then MsgBox "Thank you for your order!", 0, strMsgBoxTitle ' TODO: Actually send the order. End If End Sub Sub ValidateDeliveryDate Dim SoonestWeCanDeliver Dim RequestedDate If Not bValidOrder Then Exit Sub SoonestWeCanDeliver = Date + 2 RequestedDate = CDate(TxtDate.Value) If RequestedDate < SoonestWeCanDeliver Then bValidOrder = False MsgBox "Not even we can deliver that fast!", 0, strMsgBoxTitle End If End Sub Sub CheckSpecified(ByVal strFieldValue, ByVal strMsg) If strFieldValue = "" And bValidOrder Then MsgBox strMsg, 0, strMsgBoxTitle bValidOrder = False End If End Sub Sub BtnClear_OnClick TxtName.Value = "" TxtAddress.Value = "" TxtCity.Value = "" TxtState.Value = "" TxtZip.Value = "" TxtDate.Value = "" End Sub --> </SCRIPT>
The remaining part of the code is again all HTML. In this example all the VBScript code is encapsulated between the <SCRIPT> and </SCRIPT> tags. The entire code resides in a single location within the body of the HTML code. This makes the code modular and easy to locate. The VBScript code is listed in the <BODY> section of the HTML code.
Now let us look at the JavaScript code for the same example. The JavaScript code is included in the file jsftd.html on the companion CD-ROM. The top part of the file is again all HTML code. The only difference is in the way the buttons are declared. You'll notice an additional criteria in the <Input> tag line-OnClick. OnClick is an event associated with the buttons. It is activated when the user clicks the button.
The second half of the file is the JavaScript code. One important difference you'll notice immediately is that everything is declared as a function, whereas we had procedures (that is, subroutines) declared in the VBScript code. JavaScript does not support procedures. It supports functions only. Every function returns a value. In this example, a return value of 0 indicates success. Overall, the form and structure of the JavaScript code are similar to the VBScript code.
Refer to the following Web sites for more information on Java,
JavaScript, and VBScript. There are plenty of JavaScript and VBScript
resources and examples available on the Net for download. Both
JavaScript and VBScript are relatively new languages. You can
certainly expect enhancements and bug fixes as these languages
mature and gain developer support. Table 18.13 lists a few Web
sites that would be excellent bookmarks for keeping up-to-date
with the Java, JavaScript, and VBScript world.
Site name | Site URL |
Netscape JavaScript | http://home.netscape.com/comprod/ products/navigator/version_2.0/script/ index.html |
JavaScript Developer Tools | http://home.netscape.com/comprod/ products/navigator/version_2.0/script/ javascript_tools.html |
JavaScript Authoring Guide | http://home.netscape.com/eng/ mozilla/2.0/handbook/javascript/ index.html |
JavaScript Resources and Examples | http://home.netscape.com/comprod/ products/navigator/version_2.0/script/ script_info/index.html |
JavaScript | http://home.netscape.com/eng/mozilla/ 2.0/handbook/javascript/index.html |
VBScript | http://www.microsoft.com/vbscript |
VBScript links | http://www.microsoft.com/vbscript/ us/vbsmain/vbslinks.htm |
In this chapter you learned about Java and JavaScript. Although Java's portability and object-oriented capabilities are beneficial, there are approximately 3 million programmers who use Visual Basic as their primary programming language and who would benefit from using VBScript with their HTML code. Since VBScript is a subset of Visual Basic, these programmers would be able to port their Visual Basic code. Programming in Basic is a lot easier than in C/C++ for a number of the non-programmers. Clearly there is a need for VBScript-an easy-to-use scripting language that even non-programmers can use to build highly interactive Web pages.
In this chapter, you also learned about VBScript's programming syntax and structure. Presently VBScript is available only as part of Internet Explorer 3.0. It is available for the Windows 95, Windows NT, Windows 3.1, and Power Macintosh platforms. UNIX versions of VBScript for Sun, HP, Digital, and IBM platforms are under development. VBScript can be used with HTML code with or without ActiveX controls. It supports only one data type-a variant. You can use the function vartype to return information about the type of data stored in a variant. You can define constants in VBScript using the DIM statement. VBScript operators include arithmetic, logical, and comparison operators. The VBScript error object Err is built into it. It can be used to track runtime errors. The Err object has several properties that can be used to track and handle runtime errors. VBScript supports functions and procedures just like Visual Basic does. Functions are defined using the Function keyword. Procedures or subroutines are defined using the sub keyword. JavaScript does not support procedures.
Whether you should use Java, JavaScript, or VBScript, depends on the nature of your application and your prior programming knowledge. If you are a proficient C++ programmer, you would find Java and JavaScript interesting and easy to catch on. On the other hand, if you are a Visual Basic guru, you would appreciate its lightweight portable subset: VBScript.