Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Schongar P.VBScript unleashed.1997

.pdf
Скачиваний:
45
Добавлен:
23.08.2013
Размер:
1.59 Mб
Скачать

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."

VBScript Examples

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 Variables

VBScript supports arrays and collections of variables, similar to Visual Basic.

VBScript Operators

VBScript operators include arithmetic, comparison, and logical operators. Table 18.7 shows the VBScript arithmetic operators.

Table 18.7. VBScript arithmetic operators.

Operator

Meaning

+

Addition

-

Subtraction/negation

*

Multiplication

/

Division

\

Integer division

&

String concatenation

^

Exponentiation

mod

Remainder on division

Table 18.8 shows the VBScript comparison operators.

Table 18.8. VBScript comparison operators.

Operator

Meaning

=

Equality

<>

Non-equality

>

Greater than

>=

Greater than or equal to

<

Less than

<=

Less than or equal to

Is

Object equivalence

Table 18.9 shows the VBScript logical operators.

 

Table 18.9. VBScript logical operators.

Operator

Meaning

And

Logical AND

Or

Logical OR

Not

Logical NOT

Xor

Logical exclusion

Eqv

Logical equivalence

Imp

Logical implication

VBScript Err Object

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.

VBScript Variant Data Type

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.

 

Table 18.10. 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.

VBScript Constants

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#

VBScript Flow of Control Statements

Table 18.11 shows the VBScript flow of control statements.

 

Table 18.11. 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.

The standard If.Then.Else.End If statement.

End If

 

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 Functions

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 Procedures

VBScript supports procedures just as Visual Basic does. Procedures are defined in VBScript using the sub keyword. JavaScript does not support procedures.

ActiveX

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.

Standards and Conventions

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:

Use descriptive variable names. For example, instead of using nm for the name of a sponsor, consider using sponsor_name. Some companies use mixed-case variable names, for example Sponsor_Name. If you have been using mixed-case variable names in your previous projects, continue with it for your JavaScript and VBScript projects as well.

Use all caps to represent constants. You can prefix them with the appropriate letter to indicate whether it is an integer, a string, and so on. For example iNUMBERCONNECTIONS is an integer constant representing the number of connections.

Comment your code well, including revision history. It helps to know the kinds of changes a program has undergone and how it has evolved over time. A new developer on the project can quickly understand the nature

of change requests.

Similar to the approach of naming variables, use descriptive names for objects, procedures, and functions you declare. For example, a text box control can be named txtAddress1, where txt indicates it is a text box control and Address1 indicates it is used to store the first line of the address. Similarly, use descriptive names for procedures and functions.

Structure your script appropriately. After the script tag <SCRIPT>, an HTML comment should appear on the next line. This comment is for the old browsers that do not support any scripting language (although it would be hard to find anyone using an old browser!). If you use an HTML comment on the next line, the browser does not display the script code. When possible, use one script rather than multiple script sections throughout the page. Generally your code should appear inside the <HEAD>...</HEAD> tags. It can also appear at the bottom of your page, just before the </BODY> end-of-body tag. Having all your script in one place helps you locate it quickly and easily.

Comparing Java, JavaScript, and VBScript: A Summary

Table 18.12 summarizes the different features of Java, JavaScript, and VBScript.

Table 18.12. Java, JavaScript, and VBScript: A summary.

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

Presently supported by only

 

browsers

Internet Explorer

Steeper learning curve if not

Easy to learn

Based on BASIC

familiar with C/C++

 

 

Examples

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 CDROM. 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>