Table of Contents | Previous
| Next
| Index
This chapter contains all JavaScript functions not associated with any object. In the ECMA specification, these functions are referred to as properties and methods of the global object.
The following table summarizes the top-level functions.
Table 2.1 Top-level functions
Adds client
object property values to a dynamically generated URL or the URL used with the redirect
function.
addClient(URL)
addClient
is a top-level function and is not associated with any object.
Use addClient
to preserve client
object property values when you use redirect
or generate dynamic links. This is necessary if an application uses client or server URL encoding to maintain the client
object; it does no harm in other cases. Since the client maintenance technique can be changed after the application has been compiled, it is always safer to use addClient
, even if you do not anticipate using a URL encoding scheme.
See the Server-Side JavaScript Guide for information about using URL encoding to maintain client properties.
In the following example, addClient
is used with the redirect
function to redirect a browser:
redirect(addClient("mypage.html"))
In the following example, addClient
preserves client
object property values when a link is dynamically generated:
<A HREF='addClient("page" + project.pageno + ".html")'>
Jump to new page</A>
redirect
Adds new information to the response header sent to the client.
addResponseHeader(field, value)
addResponseHeader
is a top-level function and is not associated with any object.
You can use the addResponseHeader
function to add information to the header of the response you send to the client.
For example, if the response you send to the client uses a custom content type, you should encode this content type in the response header. The JavaScript runtime engine automatically adds the default content type (text/html
) to the response header. If you want a custom header, you must first remove the old default content type from the header and then add the new one. If your response uses royalairways-format
as a custom content type, you would specify it this way:
deleteResponseHeader("content-type");
addResponseHeader("content-type","royalairways-format");
You can use the addResponseHeader
function to add any other information you want to the response header.
Remember that the header is sent with the first part of the response. Therefore,
you should call these functions early in the script on each page. In particular,
you should ensure that the response header is set before any of these happen:
deleteResponseHeader
Assigns BLOb data to a column in a cursor.
blob (path)
A blob
object.
blob
is a top-level function and is not associated with any object.
Use this function with an updatable cursor to insert or update a row containing BLOb data. To insert or update a row using SQL and the execute
method, use the syntax supported by your database vendor.
On DB2, blobs are limited to 32 KBytes.
Remember that back slash ("\") is the escape character in JavaScript. For this reason, in NT filenames you must either use 2 backslashes or a forward slash.
The following statements update BLOb data from the specified GIF files in columns PHOTO
and OFFICE
of the current row of the EMPLOYEE
table.
// Create a cursor
cursor = database.cursor("SELECT * FROM customer WHERE
customer.ID = " + request.customerID
// Position the pointer on the row
cursor.next()
// Assign the blob data
cursor.photo = blob("c:/customer/photos/myphoto.gif")
cursor.office = blob("c:/customer/photos/myoffice.gif")
// And update the row
cursor.updateRow("employee")
Calls an external function and returns the value that the external function returns.
callC(JSFunctionName, arg1,..., argN)
callC
is a top-level function and is not associated with any object.
The callC
function returns the string value that the external function returns; callC
can only return string values.
The following example assigns a value to the variable isRegistered
according to whether the attempt to register the external function echoCCallArguments
succeeds or fails. If isRegistered
is true, the callC
function executes.
var isRegistered =
registerCFunction("echoCCallArguments",
"c:/mypath/mystuff.dll",
"mystuff_EchoCCallArguments")
if (isRegistered == true) {
var returnValue =
callC("echoCCallArguments", "first arg", 42, true, "last arg")
write(returnValue)
}
registerCFunction
Displays a JavaScript expression in the trace facility.
debug(expression)
debug
is a top-level function and is not associated with any object.
Use this function to display the value of an expression for debugging purposes. The value is displayed in the trace facility of the Application Manager following the brief description "Debug message:".
The following example displays the value of the variable data
:
debug("The final value of data is " + data)
Removes information from the header of the response sent to the client.
deleteResponseHeader(field)
deleteResponseHeader
is a top-level function and is not associated with any object.
You can use the deleteResponseHeader
function to remove information from the header of the response you send to the client. The most frequent use of this function is to remove the default content-type information before adding your own content-type information with addResponseHeader
.
For more information, see addResponseHeader
.
Returns the hexadecimal encoding of an argument in the ISO-Latin-1 character set.
escape("string")
escape
is a top-level function and is not associated with any object.
Use the escape
and unescape
functions to encode and decode (add property values manually) a Uniform Resource Locator (URL), a Uniform Resource Identifier (URI), or a URI-type string.
The escape
function encodes special characters in the specified string and returns the new string. It encodes spaces, punctuation, and any other character that is not an ASCII alphanumeric character, with the exception of these characters:
* @ - _ + . /
Example 1. The following example returns "%26"
:
escape("&") // returns "%26"
Example 2. The following statement returns a string with encoded characters for spaces, commas, and apostrophes.
// returns "The_rain.%20In%20Spain%2C%20Ma%92am"
escape("The_rain. In Spain, Ma'am")
Example 3. In the following example, the value of the variable theValue
is encoded as a hexadecimal string and passed on to the request
object when a user clicks the link:
<A HREF='"mypage.html?val1="+escape(theValue)')>Click Here</A>
unescape
Evaluates a string of JavaScript code without reference to a particular object.
eval(string)
eval
is a top-level function and is not associated with any object.
The argument of the eval
function is a string. If the string represents an expression, eval
evaluates the expression. If the argument represents one or more JavaScript statements, eval
performs the statements. Do not call eval
to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.
If you construct an arithmetic expression as a string, you can use eval
to evaluate it at a later time. For example, suppose you have a variable x
. You can postpone evaluation of an expression involving x
by assigning the string value of the expression, say "3 * x + 2"
, to a variable, and then calling eval
at a later point in your script.
If the argument of eval
is not a string, eval
returns the argument unchanged. In the following example, the String
constructor is specified, and eval
returns a String
object rather than evaluating the string.
eval(new String("2+2")) // returns a String object containing "2+2"
eval("2+2") // returns 4
JavaScript 1.1.
eval
is also a method of all objects. This method is described for the Object
class.
The following examples display output using document.write
. In server-side JavaScript, you can display the same output by calling the write
function instead of using document.write
.
Example 1. In the following code, both of the statements containing eval
return 42. The first evaluates the string "x + y + 1"
; the second evaluates the string "42"
.
var x = 2
var y = 39
var z = "42"
eval("x + y + 1") // returns 42
eval(z) // returns 42
Example 2. In the following example, the getFieldName(n)
function returns the name of the specified form element as a string. The first statement assigns the string value of the third form element to the variable field
. The second statement uses eval
to display the value of the form element.
var field = getFieldName(3)
document.write("The field named ", field, " has value of ",
eval(field + ".value"))
Example 3. The following example uses eval
to evaluate the string str
. This string consists of JavaScript statements that open an Alert dialog box and assign z
a value of 42 if x
is five, and assigns 0 to z
otherwise. When the second statement is executed, eval
will cause these statements to be performed, and it will also evaluate the set of statements and return the value that is assigned to z
.
var str = "if (x == 5) {alert('z is 42'); z = 42;} else z = 0; "
document.write("<P>z is ", eval(str))
Example 4. In the following example, the setValue
function uses eval
to assign the value of the variable newValue
to the text field textObject
:
function setValue (textObject, newValue) {
eval ("document.forms[0]." + textObject + ".value") = newValue
}
Example 5. The following example creates breed
as a property of the object myDog
, and also as a variable. The first write statement uses eval('breed')
without specifying an object; the string "breed"
is evaluated without regard to any object, and the write
method displays "Shepherd"
, which is the value of the breed
variable. The second write statement uses myDog.eval('breed')
which specifies the object myDog
; the string "breed"
is evaluated with regard to the myDog
object, and the write
method displays "Lab"
, which is the value of the breed
property of the myDog
object.
function Dog(name,breed,color) {
this.name=name
this.breed=breed
this.color=color
}
myDog = new Dog("Gabby")
myDog.breed="Lab"
var breed='Shepherd'
document.write("<P>" + eval('breed'))
document.write("<BR>" + myDog.eval('breed'))
Object.eval
method
Sends data from the internal buffer to the client.
flush()
None.
flush
is a top-level function and is not associated with any object.
To improve performance, JavaScript buffers the HTML page it constructs. The flush
function immediately sends data from the internal buffer to the client. If you do not explicitly call the flush
function, JavaScript sends data to the client after each 64KB of content in the constructed HTML page.
Use the flush
function to control when data is sent to the client. For example, call the flush
function before an operation that creates a delay, such as a database query. If a database query retrieves a large number of rows, you can flush the buffer after retrieving a small number of rows to prevent long delays in displaying data.
Because the flush
function updates the client's cookie file as part of the HTTP
header, you should perform any changes to the client
object before flushing
the buffer, if you are using client cookie to maintain the client
object. For
more information, see the Server-Side JavaScript Guide.
Do not confuse the flush
method of the File
object with the top-level flush
function.
The following example iterates through a text file and outputs each line in the file, preceded by a line number and five spaces. The flush
function then causes the client to display the output.
while (!In.eof()) {
AscLine = In.readln();
if (!In.eof())
write(LPad(LineCount + ": ", 5), AscLine, "\n");
LineCount++;
flush();
}
write
Returns the text of a selected OPTION
in a SELECT
form element.
getOptionValue(name, index)
A string containing the text for the selected option, as specified by the associated OPTION
tag.
getOptionValue
is a top-level function and is not associated with any object. It corresponds to the Option.text
property available to client-side JavaScript.
The SELECT
tag allows multiple values to be associated with a single form element, with the MULTIPLE
attribute. If your application requires select lists that allow multiple selected options, you use the getOptionValue
function to get the values of selected options in server-side JavaScript.
Suppose you have the following form element:
<SELECT NAME="what-to-wear" MULTIPLE SIZE=8>
<OPTION SELECTED>Jeans
<OPTION>Wool Sweater
<OPTION SELECTED>Sweatshirt
<OPTION SELECTED>Socks
<OPTION>Leather Jacket
<OPTION>Boots
<OPTION>Running Shoes
<OPTION>Cape
</SELECT>
You could process the input from this select list in server-side JavaScript as follows:
<SERVER>
var loopIndex = 0
var loopCount = getOptionValueCount("what-to-wear") // 3 by default
while ( loopIndex < loopCount ) {
var optionValue = getOptionValue("what-to-wear",loopIndex)
write("<br>Item #" + loopIndex + ": " + optionValue + "\n")
loopIndex++
}
</SERVER>
If the user kept the default selections, this script would return
Item #1: Jeans
Item #3: Sweatshirt
Item #4: Socks
getOptionValueCount
Returns the number of options selected by the user in a SELECT
form element.
getOptionValueCount(name)
getOptionValueCount
is a top-level function and is not associated with any object.
Use this function with getOptionValue
to process user input from SELECT
form elements that allow multiple selections.
See the example for getOptionValue
.
getOptionValue
Evaluates an argument to determine if it is not a number.
isNaN(testValue)
isNaN
is a top-level function and is not associated with any object.
On platforms that support NaN, the parseFloat
and parseInt
functions return NaN
when they evaluate a value that is not a number. isNaN
returns true if passed NaN
, and false otherwise.
The following example evaluates floatValue
to determine if it is a number and then calls a procedure accordingly:
floatValue=parseFloat(toFloat)
if (isNaN(floatValue)) {
notFloat()
} else {
isFloat()
}
Number.NaN
, parseFloat
, parseInt
Converts the specified object to a number.
Number(obj)
Number
is a top-level function and is not associated with any object.
When the object is a Date
object, Number
returns a value in milliseconds measured from 01 January, 1970 UTC (GMT), positive after this date, negative before.
If obj
is a string that does not contain a well-formed numeric literal, Number
returns NaN.
The following example converts the Date
object to a numerical value:
d = new Date ("December 17, 1995 03:24:00")
alert (Number(d))
This displays a dialog box containing "819199440000."
Number
Parses a string argument and returns a floating point number.
parseFloat(string)
parseFloat
is a top-level function and is not associated with any object.
parseFloat
parses its argument, a string, and returns a floating point number. If it encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters. Leading and trailing spaces are allowed.
If the first character cannot be converted to a number, parseFloat
returns NaN
.
For arithmetic purposes, the NaN
value is not a number in any radix. You can call the isNaN
function to determine if the result of parseFloat
is NaN
. If NaN
is passed on to arithmetic operations, the operation results will also be NaN
.
The following examples all return 3.14:
parseFloat("3.14")
parseFloat("314e-2")
parseFloat("0.0314E+2")
var x = "3.14"
parseFloat(x)
The following example returns NaN
:
parseFloat("FF2")
isNaN
, parseInt
Parses a string argument and returns an integer of the specified radix or base.
parseInt(string[, radix])
parseInt
is a top-level function and is not associated with any object.
The parseInt
function parses its first argument, a string, and attempts to return an integer of the specified radix (base). For example, a radix of 10 indicates to convert to a decimal number, 8 octal, 16 hexadecimal, and so on. For radixes above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.
If parseInt
encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt
truncates numbers to integer values. Leading and trailing spaces are allowed.
If the radix is not specified or is specified as 0, JavaScript assumes the following:
If the first character cannot be converted to a number, parseInt
returns NaN
.
For arithmetic purposes, the NaN
value is not a number in any radix. You can call the isNaN
function to determine if the result of parseInt
is NaN
. If NaN
is passed on to arithmetic operations, the operation results will also be NaN
.
The following examples all return 15:
parseInt("F", 16)
parseInt("17", 8)
parseInt("15", 10)
parseInt(15.99, 10)
parseInt("FXX123", 16)
parseInt("1111", 2)
parseInt("15*3", 10)
The following examples all return NaN
:
parseInt("Hello", 8)
parseInt("0x7", 10)
parseInt("FFF", 10)
Even though the radix is specified differently, the following examples all return 17 because the input string
begins with "0x"
.
parseInt("0x11", 16)
parseInt("0x11", 0)
parseInt("0x11")
isNaN
, parseFloat
, Object.valueOf
Redirects the client to the specified URL.
redirect(location)
redirect
is a top-level function and is not associated with any object.
The redirect
function redirects the client browser to the URL specified by the location
parameter. The value of location
can be relative or absolute.
When the client encounters a redirect
function, it loads the specified page immediately and discards the current page. The client does not execute or load any HTML or script statements in the page following the redirect
function.
You can use the addClient
function to preserve client
object property values. See addClient
for more information.
The following example uses the redirect
function to redirect a client browser:
redirect("http://www.royalairways.com/lw/apps/newhome.html")
The page displayed by the newhome.html
link could contain content such as the following:
<H1>New location</H1>
The URL you tried to access has been moved to:<BR>
<LI><A HREF=http://www.royalairways.com/lw/apps/index.html>
http://www.royalairways.com/lw/apps/index.html</A>
<P>This notice will remain until 12/31/97.
addClient
Registers an external function for use with a server-side JavaScript application.
registerCFunction(JSFunctionName, libraryPath,
externalFunctionName)
registerCFunction
is a top-level function and is not associated with any object.
Use registerCFunction
to make an external function available to a server-side JavaScript application. The function can be written in any language, but you must use C calling conventions.
To use an external function in a server-side JavaScript application, register the function with registerCFunction
, and then call it with the callC
function. Once an application registers a function, you can call the function any number of times.
The registerCFunction
function returns true if the external function is registered successfully; otherwise, it returns false. For example, registerCFunction
can return false if the JavaScript runtime engine cannot find either the library or the specified function inside the library.
To use a backslash (\) character as a directory separator in the libraryPath
parameter, you must enter a double backslash (\\). The single backslash is a reserved character.
See the example for the callC
function.
callC
Returns a unique string you can use to uniquely specify the client
object.
ssjs_generateClientID()
None.
ssjs_generateClientID
is a top-level function and is not associated with any object.
This function is closely related to ssjs_getClientID
. See the description of that function for information on these functions and the differences between them.
Returns the value of the specified environment variable set in the server process, including some CGI variables.
ssjs_getCGIVariable(varName)
ssjs_getCGIVariable
is a top-level function and is not associated with any object.
ssjs_getCGIVariable
lets you access the environment variables set in the server process, including the CGI variables listed in the following table.
Table 2.2 CGI variables accessible through ssjs_getCGIVariable
Variable
|
Description
AUTH_TYPE |
The authorization type, if the request is protected by any type of authorization. Netscape web servers support HTTP basic access authorization. Example value: basic
| HTTPS |
If security is active on the server, the value of this variable is ON ; otherwise, it is OFF . Example value: ON
| HTTPS_KEYSIZE |
The number of bits in the session key used to encrypt the session, if security is on. Example value: 128
| HTTPS_SECRETKEYSIZE |
The number of bits used to generate the server's private key. Example value: 128
| PATH_INFO |
Path information, as sent by the browser. Example value: /cgivars/cgivars.html
| PATH_TRANSLATED |
The actual system-specific pathname of the path contained in PATH_INFO . Example value: /usr/ns-home/myhttpd/js/samples/cgivars/cgivars.html
| QUERY_STRING |
Information from the requesting HTML page; if "?" is present, the information in the URL that comes after the "?". Example value: x=42
| REMOTE_ADDR |
The IP address of the host that submitted the request. Example value: 198.93.95.47
| REMOTE_HOST |
If DNS is turned on for the server, the name of the host that submitted the request; otherwise, its IP address. Example value: www.netscape.com
| REMOTE_USER |
The name of the local HTTP user of the web browser, if HTTP access authorization has been activated for this URL. Note that this is not a way to determine the user name of any person accessing your program. Example value: ksmith
| REQUEST_METHOD |
The HTTP method associated with the request. An application can use this to determine the proper response to a request. Example value: GET
| SCRIPT_NAME |
The pathname to this page, as it appears in the URL. Example value: cgivars.html
| SERVER_NAME |
The hostname or IP address on which the JavaScript application is running, as it appears in the URL. Example value: piccolo.mcom.com
| SERVER_PORT |
The TCP port on which the server is running. Example value: 2020
| SERVER_PROTOCOL |
The HTTP protocol level supported by the client's software. Example value: HTTP/1.0
| SERVER_URL |
The URL that the user typed to access this server. Example value: https://piccolo:2020
| |
---|
If you supply an argument that isn't one of the CGI variables listed in n, the runtime engine looks for an environment variable by that name in the server environment. If found, the runtime engine returns the value; otherwise, it returns null. For example, the following code assigns the value of the standard CLASSPATH
environment variable to the JavaScript variable classpath
:
classpath = ssjs_getCGIVariable("CLASSPATH");
Returns the identifier for the client
object used by some of JavaScript's client-maintenance techniques.
ssjs_getClientID()
None.
ssjs_getClientID
is a top-level function and is not associated with any object.
For some applications, you may want to store information specific to a client/application pair in the project
or server
objects. In these situations, you need a way to refer uniquely to the client/application pair. JavaScript provides two functions for this purpose, ssjs_generateClientID
and ssjs_getClientID
.
Each time you call ssjs_generateClientID
, the runtime engine returns a new identifier. For this reason, if you use this function and want the identifier to last longer than a single client request, you need to store the identifier, possibly as a property of the client
object.
If you use this function and store the ID in the client
object, you may need to be careful that an intruder cannot get access to that ID and hence to sensitive information.
An alternative approach is to use the ssjs_getClientID
function. If you use one of the server-side maintenance techniques for the client
object, the JavaScript runtime engine generates and uses a identifier to access the information for a particular client/application pair.
When you use these maintenance techniques, ssjs_getClientID
returns the identifier used by the runtime engine. Every time you call this function from a particular client/application pair, you get the same identifier. Therefore, you do not need to store the identifier returned by ssjs_getClientID
. However, if you use any of the other maintenance techniques, this function returns "undefined"; if you use those techniques you must instead use the ssjs_generateClientID
function.
If you need an identifier and you're using a server-side maintenance technique, you probably should use the ssjs_getClientID
function. If you use this function, you do not need to store and track the identifier yourself; the runtime engine does it for you. However, if you use a client-side maintenance technique, you cannot use the ssjs_getClientID
function; you must use the ssjs_generateClientID
function.
Converts the specified object to a string.
String(obj)
String
is a top-level function and is not associated with any object.
The String
method converts the value of any object into a string; it returns the same value as the toString
method of an individual object.
When the object is a Date
object, String
returns a more readable string representation of the date. Its format is: Thu Aug 18 04:37:43 Pacific Daylight Time 1983.
The following example converts the Date
object to a readable string.
D = new Date (430054663215)
alert (String(D))
This displays a dialog box containing "Thu Aug 18 04:37:43 GMT-0700 (Pacific Daylight Time) 1983."
String
Returns the ASCII string for the specified hexadecimal encoding value.
unescape(string)
unescape
is a top-level function and is not associated with any object.
The string returned by the unescape
function is a series of characters in the ISO-Latin-1 character set.
In server-side JavaScript, use this function to decode name/value pairs in URLs.
The following example returns "&"
:
unescape("%26")
The following example returns "!#"
:
unescape("%21%23")
In the following example, val1
has been passed to the request
object as a hexadecimal value. The statement assigns the decoded value of val1
to myValue
.
myValue = unescape(request.val1)
escape
Generates HTML based on an expression and sends it to the client.
write(expression)
write
is a top-level function and is not associated with any object.
The write
function causes server-side JavaScript to generate HTML that is sent to the client. The client interprets this generated HTML as it would static HTML. The server-side write
function is similar to the client-side document.write
method.
To improve performance, the JavaScript engine on the server buffers the output to be sent to the client and sends it in large blocks of at most 64 KBytes in size. You can control when data are sent to the client by using the flush
function.
Do not confuse the write
method of the File
object with the write
function. The write
function outputs data to the client; the write
method outputs data to a physical file on the server.
In the following example, the write
function is passed a string, concatenated with a variable, concatenated with a BR
tag:
write("The operation returned " + returnValue + "<BR>")
If returnValue
is 57, this example displays the following:
The operation returned 57
flush
Table of Contents | Previous
| Next
| Index
Last Updated: 11/13/98 10:24:03
Copyright (c) 1998
Netscape Communications Corporation