Вы находитесь на странице: 1из 33

Web Development Technologies

Recapture
<html>
<head>
<title>Hi ni page yet Lets Try</title>
</head>
<body>
<table width="1006" border="0" cellpadding="0" cellspacing="0">
<tr>
<td height="44" colspan="2" valign="top"><div align="center">Please Try this it really works </div></td>
</tr>
<tr>
<td width="285" height="390" valign="top"><p>Put some text here. Paste some more or type </p>
<p><a href="Test Page.html">Link 1</a></p>
<p><a href="Test Page.html">Link 2 </a></p>
<p><a href="Test Page.html">Link 3</a></p>
<p><a href="Test Page.html">Link 4</a></p>
<p><a href="Test Page.html">Link 5</a></p>
<p>&nbsp; </p></td>
<td width="721" valign="top"><p align="justify">The <strong>Internet Server Application Programming
Interface</strong> (<strong>ISAPI</strong>) is an N-tier API of Internet Information Services (IIS),
Microsoft's collection of Windows-based web server services. The most prominent application of IIS and
ISAPI is Microsofts web server.<br/>
The ISAPI has also been implemented by Apache's mod_isapi module so that server-side web
applications written for Microsoft's IIS can be used with Apache, and other third-party web servers like
Zeus Web Server offer ISAPI interfaces.<br />
Microsoft's web server application software is called Internet Information Services, which is made up of
a number of &quot;sub-applications&quot; and is very configurable. ASP.NET is one such slice of IIS,
allowing a programmer to write web applications in his or her choice of programming language (VB.NET,
C#, F#) that's supported by the Microsoft .NET CLR. <strong>ISAPI</strong> is a much lower-level
programming system, giving much better performance, at the expense of simplicity.</p></td>
</tr>
</table>
</body>
</html>

1
CK

Web Development Technologies

Lets Try Forms


<td valign="top"><form id="form1" name="form1" method="post" action="">
<label><strong>StudentID
</strong>
<input name="txtStudentID" type="text" id="txtStudentID" />
</label>
<p>
<label><strong>Student Name</strong>
<input name="txtStudentName" type="text" id="txtStudentName" />
</label>
</p>
<p>
<label><strong>Course</strong>
<select name="cbocourse" id="cbocourse">
<option>BSC IT</option>
<option>BBIT</option>
<option>Computer Science</option>
2
CK

Web Development Technologies


<option>BCOM</option>
<option>Arts</option>
</select>
</label>
</p>
<p><strong>Mode of Study </strong></p>
<p>
<label>
<input type="radio" name="Mode of Study" value="radio" />
Evening</label>
<br />
<label>
<input type="radio" name="Mode of Study" value="radio" />
Day</label>
<br />
<label>
<input type="radio" name="Mode of Study" value="radio" />
Weekend</label>
<br />
</p>
<p>
<label><strong>Interests and Hobies</strong></label>
</p>
<p>
<label>
<input name="chkftball" type="checkbox" id="chkftball" value="checkbox" />
</label>
Footaball
<label>
<input name="chksinging" type="checkbox" id="chksinging" value="checkbox" />
Singing</label>
<label>
<input name="chkdancing" type="checkbox" id="chkdancing" value="checkbox" />
Dancing</label>
<label>
<input name="chkdancing" type="checkbox" id="chkdancing" value="checkbox" />
Swimming</label>
</p>
<p>Comments</p>
<p>
<label>
<textarea name="Comments" cols="50" rows="5" id="Comments"></textarea>
</label>
</p>
<p>
<label>Submit
<input type="submit" name="Submit" value="Submit" />
</label>
3
CK

Web Development Technologies


</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</form></td>

4
CK

Web Development Technologies

Server Side Scripting


Create a table called students with the attributes (field names) as shown in the form below:-

<form id="form1" name="form1" method="post" action="saveform.php">


<label><strong>StudentID
</strong>
<input name="txtStudentID" type="text" id="txtStudentID" />
</label>
<p>
<label><strong>Student Name</strong>
<input name="txtStudentName" type="text" id="txtStudentName" />
</label>
</p>
<p>
<label><strong>Course</strong>
<select name="cbocourse" id="cbocourse">
5
CK

Web Development Technologies


<option>BSC IT</option>
<option>BBIT</option>
<option>Computer Science</option>
<option>BCOM</option>
<option>Arts</option>
</select>
</label>
</p>
<p>
<label></label>
</p>
<p>Comments</p>
<p>
<label>
<textarea name="Comments" cols="50" rows="5" id="Comments"></textarea>
</label>
</p>
<p>
<label>Submit
<input type="submit" name="Submit" value="Submit" />
</label>
</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</form>

<?php
$StudentID=$_POST["txtStudentID"];
$StudentName=$_POST["txtStudentName"];
$Course=$_POST["cbocourse"];
$Comments=$_POST["Comments"];
$con=mysql_connect("localhost","root","");
mysql_select_db("TestData",$con);
mysql_query("insert into students(StudentID,StudentName, Course, Comments)
values('$StudentID','$StudentName','$Course','$Comments')");
mysql_close($con);
echo "Data Posted Successfully and Saved Students Table";
?>

6
CK

Web Development Technologies


Introduction to scripts
A client-side script is a program that may accompany an HTML document or be embedded directly
in it. The program executes on the client's machine when the document loads, or at some other
time such as when a link is activated. HTML's support for scripts is independent of the scripting
language.
Scripts offer authors a means to extend HTML documents in highly active and interactive ways.
For example:

Scripts may be evaluated as a document loads to modify the contents of the document
dynamically.
Scripts may accompany a form to process input as it is entered. Designers may dynamically
fill out parts of a form based on the values of other fields. They may also ensure that input
data conforms to predetermined ranges of values, that fields are mutually consistent, etc.
Scripts may be triggered by events that affect the document, such as loading, unloading,
element focus, mouse movement, etc.
Scripts may be linked to form controls (e.g., buttons) to produce graphical user interface
elements.

There are two types of scripts authors may attach to an HTML document:
Those that are executed one time when the document is loaded by the user agent. Scripts
that appear within a SCRIPT element are executed when the document is loaded. For user
agents that cannot or will not handle scripts, authors may include alternate content via the
NOSCRIPT element.
Those that are executed every time a specific event occurs. These scripts may be assigned
to a number of elements via the intrinsic event attributes.

i.

ii.

Uses of Scripting Languages


Scripting languages are used to make the process of creating a program faster and easier. Instead
of going through the process of creating each individual sequence, a scripting language will run a
number of sequences in one batch.

Below are certain uses this can be applied to.


i.

Alerts - This is an event based sequence where something has happened causing the
alert message to pop up. For example the file can be scripted to make this pop up when
a webpage is opened saying something along the lines of 'Welcome!'

7
CK

Web Development Technologies


ii.

iii.

iv.

Redirecting the user - This is a simple use for scripting languages. For example if a page
no longer exists, the user can be redirected from that page to another fully functioning
one.
Browser Detection - The navigator object determines which platform a scripting
language will be working with, using browser detection is very necessary considering
there are old browsers out there which will not be the same as some of the newer
ones. Using this can make the information displayed appropriate for the user.
Maintaining cookies - Cookies are what remember little sets of data so that when you
visit a site it remembers for example what you put in the box for your first name on a
registration field. By telling the scripting language to do this you can set it to last for
however long you want, a few days, a few months, or just until the page is exited by
leaving the space blank.

Client-side Scripting Environment (Browsers and Editors)


The World Wide Web (WWW) began as a text-only medium-the first browsers didn't even
support images within web pages.
Today's websites can include a lot of features: graphics, sounds, animation, video, and
occasionally useful content. Web scripting languages also known as client-side scripting
languages, such as JavaScript, are one of the easiest ways to add dynamic state to a web page
and to interact with users in new ways.

Introducing JavaScript
JavaScript was developed by Netscape Communications Corporation, the maker of the Netscape
web browser. JavaScript was the first web scripting language to be supported by browsers, and it
is still by far the most popular.
JavaScript was originally called LiveScript and was first introduced in Netscape Navigator 2.0 in
1995. Netscape Navigator was an early browser that held a large share of the browser market.

Here are a few of the things you can do with JavaScript:


Display messages to the user as part of a web page, in the browser's status line, or in alert
boxes.
Validate the contents of a form and make calculations (for example, an order form can
automatically display a running total as you enter item quantities).
8
CK

Web Development Technologies

Animate images or create images that change when you move the mouse over them.
Create ad banners that interact with the user, rather than simply displaying a graphic.
Detect the browser in use or its features and perform advanced functions only on browsers
that support them.
Detect installed plug-ins and notify the user if a plug-in is required.
Modify all or part of a web page without requiring the user to reload it.
Display or interact with data retrieved from a remote server.

JavaScript and the Document Object Model


When a JavaScript interpreter is embedded in a web browser, the result is client-side JavaScript.
This is by far the most common variant of JavaScript; when most people refer to JavaScript, they
usually mean client-side JavaScript.
Client-side JavaScript combines the scripting ability of a JavaScript interpreter with the Document
Object Model (DOM) defined by a web browser. Documents may contain JavaScript scripts, and
those scripts can use the DOM to modify the document or control the web browser that displays
the document.
The client-side JavaScript adds behavior to otherwise static web content. Client-side JavaScript is
at the heart of web development techniques such as DHTML and architectures such as Ajax.
The World Wide Web Consortium (W3C) has published a DOM specification that standardizes the
features a browser must support in its DOM.

Browsers
If you are developing a web application using a client-side scripting language then you will need to
ensure cross compatibility amongst browser. A browser is where the script will run. As browser
are constantly being updated, so too are the version of scripting language that is run inside them.
Common scripting languages that run inside browsers are
JavaScript and VBscript, the online materials you are reading will focus on Javascript
as this language is available across a variety of browsers.
VBscript is developed by Microsoft and is available only on the Internet Explorer
browsers.

9
CK

Web Development Technologies


Characteristics of Interpreted Languages
One of the main benefits of interpreted languages is that they require no compilation. The
language is interpreted at run-time so the instructions are executed immediately.
Any errors in an interpreted program will result in the execution of the code to be halted.
Interpreted languages also have a simple syntax which, for the user:

makes them easy to learn and use


assumes minimum programming knowledge or experience
allows complex tasks to be performed in relatively few steps
allows simple creation and editing in a variety of text editors
allows the addition of dynamic and interactive activities to web pages

Also, interpreted languages are generally portable across various hardware and network platforms
and scripts can be embedded in standard text documents for added functionality.
Unlike a compiler, an interpreter checks syntax and generates object code one source line at a
time. Think of this as very similar to a group of translators at a United Nations' Conference, who
each have to convert sentences spoken by delegates into the native language of their
representative.
When an error is encountered, the interpreter immediately feeds back information on the type of
error and stops interpreting the code. This allows the programmer to see instantly the nature of
the error and where it has occurred. He or she can then make the necessary changes to the source
code and have it re-interpreted.
As the interpreter executes each line of code at a time the programmer is able to see the results
of their programs immediately which can also help with debugging.

Features and Characteristics of Compiled Languages


A compiled language is a programming language whose implementations are typically compilers
(translators which generate machine code from source code), and not interpreters (step-by-step
executors of source code, where no translation takes place).
The term is a little vague; in principle any language can be implemented with a compiler or with
an interpreter. A combination of both solutions is also increasingly common: a compiler can
10
CK

Web Development Technologies


translate the source code into some intermediate form (often called bytecode, as is the case with
the language of JAVA), which is then passed to an interpreter which executes it.
A program translated by a compiler tends to be much faster than an interpreter executing the
same program.
The mixed solution's efficiency is typically somewhere in between. The downsides of the
"compiler" solution are the inherent complexity of a good implementation and the longer time it
takes to create , edit and compile a program from source code.
A closer look at the operations of the back end of a compiled language reveals:
intermediate code generation
code optimization
machine code generation
This results in a more efficient and faster execution of the code
A pure compiler implementation is the typical solution for low-level languages, such as C. This is
preferred with such languages as speed is a major requirement.

Advantages and Disadvantages of Interpreted Languages


Advantages

easy to learn and use


minimum programming knowledge or experience
allows complex tasks to be performed in relatively few steps
allows simple creation and editing in a variety of text editors
allows the addition of dynamic and interactive activities to web pages
Edit and running of code is fast.

Disadvantages
usually run quite slowly
Limited access to low level and speed optimization code.
Limited commands to run detailed operations on graphics.

11
CK

Web Development Technologies


Advantages and Disadvantages of Compiled Languages
Advantages
fast execution
optimized for the target hardware
Disadvantages
require a compiler
Editing and deploying the code is a lot slower than interpreters.

Main Differences between Interpreters and Compilers


i.

The main difference between an interpreter and a compiler is that compilation


requires analysis and the generation of machine code only once, whereas an
interpreter may need to analyze and interpret the same program statements
each time it meets them e.g. instructions appearing within a loop. For example
the following Visual Basic code would be interpreted each time the loop is
entered:

For iCountvar = To 20
iSum = iSum + iCountvar
Pic.Display iSum
Next iCountvar

This has implications for error reporting, eg: when an interpreter encounters an error it
reports it to the user immediately and halts further execution of the program. Such instant
feedback, pinpointing the exact location of the error, helps the programmer to find and
remove errors.
Compilers, on the other hand, analyze the entire program, taking note of where errors
have occurred, and places these in an error/diagnostic file. If errors have occurred then
the program cannot run. Programmers must then use the error messages to identify and
remove the errors in the source code. Some compilers assist by adding line numbers to the
source listing to help pinpoint errors and all compilers will describe the nature of the error
e.g. missing semi-colon, expected keyword, etc. - although interpreting some compiler
diagnostics is a skill in itself.

12
CK

Web Development Technologies


ii.

iii.

iv.

Error correction can be very time-consuming and frustrating, particularly in the


case where spurious errors occur, e.g. many errors are highlighted in the source
but the cause of the error is a single, simple mistake. An example of this would
be errors that are generated by, say, a compiler, if a programmer simply misses
out a semi-colon.
Another important difference is that interpreters can be 2 to 10 times slower
than compilers. One reason for this is that they translate the same statements
within a loop over and over again. Compilers can produce much more efficient
object code than interpreters thus making the compiled programs to run faster.
Interpreters however are easier to use, particularly for beginners, since errors
are immediately displayed, corrected by the user, until the program is able to
be executed. On the whole compilers tend to be more difficult to use.

Differences between Client-side and Server-side Scripting


Client-side Environment (Scripting)
The client-side environment used to run scripts is usually a browser. The processing takes place
on the end users computer. The source code is transferred from the web server to the users
computer over the internet and run directly in the browser.
The scripting language needs to be enabled on the client computer. Sometimes if a user is
conscious of security risks they may switch the scripting facility off. When this is the case a message
usually pops up to alert the user when script is attempting to run.

Server-side Environment (Scripting)


The server-side environment that runs a scripting language is a web server. A user's request is
fulfilled by running a script directly on the web server to generate dynamic HTML pages. This HTML
is then sent to the client browser. It is usually used to provide interactive web sites that interface
to databases or other data stores on the server.
This is different from client-side scripting where scripts are run by the viewing web browser,
usually in JavaScript. The primary advantage to server-side scripting is the ability to highly
customize the response based on the user's requirements, access rights, or queries into data
stores.
13
CK

Web Development Technologies

Tools for Producing and Running Scripts


The tools needed to produce client-side scripts and server-side scripts can be as simple as a
notepad.
To maximize the full capabilities of what a server-side script can do, it is necessary to use a
professional integrated development environment (IDE). There are various IDE's available,
depending on the language you will be using and what resources will be accessed.
If you plan to use Visual Basic, then the Microsoft tools are ideal. Microsoft Visual Studio or the
VB.Net applications.
These applications help to speed development through the use of wizards that auto generate code
as you visually link components etc.

On-line Database Accessibility


If you want to link your application to a database then you must make use of server-side scripting.
The tools make it easy to link to databases.
Web Database follows the client-server database model. A Database Engine sits on some central
computer somewhere and serves data to multiple web-based clients (perhaps lots of customers
using Netscape Navigator).
Because we are dealing with web-based clients however, we must also have a Web Server that
handles requests from web-browsers and then forwards them to the Database. Likewise, the web
server will wait for the database to respond and then pass on that response to the waiting web
browsers. The whole interaction is much simpler as a picture.

Of course, the problem with the above model is that it does not exactly tell the whole story.
Actually, though Web Servers are built to talk to Web Browsers, they are not built to talk to
Databases. Thus, in order for the Web Server to talk to a Database, it requires a helper (sometimes
called Middle Ware).
The most basic type of Middle Ware is a CGI script that is written to translate requests from the
Web Server to a format that the Database can understand, and to translate Database responses
14
CK

Web Development Technologies


into something the Web Server can send back out to the Web Browser and that the person using
the web browser can understand.
The CGI Script will be responsible for understanding what the Web Server is saying and will also
be responsible for knowing how to talk to the Database. Of course, the CGI script can be written
in any computer programming language and can use all sorts of inventive or proprietary methods
to talk to the Database.

Types of scripting languages


Specialized scripting languages include:
Perl (Practical Extraction and Report Language). This is a popular string processing language for
writing small scripts for system administrators and web site maintainers. Much web development
is now done using Perl.
Hypertalk is another example. It is the underlying scripting language of HyperCard.
Lingo is the scripting language of Macromedia Director, an authoring system for develop highperformance multimedia content and applications for CDs, DVDs and the Internet.
AppleScript, a scripting language for the Macintosh allows the user to send commands to the
operating system to, for example open applications, carry out complex data operations.
JavaScript, perhaps the most publicised and well-known scripting language was initially developed
by Netscape as LiveScript to allow more functionality and enhancement to web page authoring
that raw HTML could not accommodate. A standard version of JavaScript was later developed to
work in both Netscape and Microsoft's Internet Explorer, thus making the language to a large
extent, universal. This means that JavaScript code can run on any platform that has a JavaScript
interpreter.
VBScript, a cut-down version of Visual Basic, used to enhance the features of web pages in Internet
Explorer.

15
CK

Web Development Technologies

Advantages and Disadvantages of Scripting Languages


Scripting languages are becoming more popular due to the emergence of web-based applications.
The market for producing dynamic web content is now expanding extremely rapidly such that new
scripting languages have been developed to allow users with little or no programming expertise
to develop interactive web pages with minimum effort.
Also the increases in computer performance over the past few years has promoted a increase in
the power and sophistication of scripting languages that, unlike conventional programming
languages, can even have certain security features built-in.
Major advantages of scripting languages include:

easy to learn and use


minimum programming knowledge or experience required
allow complex tasks to be performed in relatively few steps
allow simple creation and editing in a variety of text editors
allow the addition of dynamic and interactive activities to web pages
Editing and running code is fast.

The major disadvantage of scripting languages is that executable code can inadvertently be
downloaded from a remote server to a web browser's machine, installed and run using the local
browser's interpreter. This is easily done by visiting dubious web sites or downloading programs
without valid authenticity. The user is probably unaware of anything devious occurring.
This is a weakness and major drawback in the formal rules defining scripting languages like
JavaScript and VBScript.

Uses of Scripting Languages


Typical uses of scripting languages including JavaScript include:
1. Image or text rollovers: If the user rolls the mouse over a graphic or hypertext then a text
or graphic box will appear:
2. Creating a pop-up window to display information in a separate window from the Web page
that triggered it. This is useful if the user requires to perform a simple calculation or consult

16
CK

Web Development Technologies


a calendar for inputting dates. This is achieved by embedding ActiveX controls or Java
applets into the script.

3. Validating the content of fields: When filling in forms, each field, especially required fields
denoted by an asterisk, are validated for correct input. If the field is left blank or incorrect
information entered then a user message will be generated and you may not continue.

Methods Used to Implement Client-side Scripts


Client-side JavaScript code can be embedded within HTML documents in a number of ways:
Between a pair of script tags
From an external file specified by the src attribute of a script tag
In an event handler, specified as the value of an HTML attribute such as onclick or
onmouseover
In a URL that uses the special javascript: protocol

<html>
17
CK

Web Development Technologies


<head>
<title>Today's Date</title>
<script language="JavaScript">
// Define a function for later use
function print_todays_date( ) {
var d = new Date( );
// Get today's date and time
document.write(d.toLocaleString( )); // Insert it into the document
}
</script>
</head>
<body>
The date and time are:<br/>
<script language="JavaScript">
// Now call the function we defined above
print_todays_date( );
</script>
</html>

Starting JAVA Script


JavaScript is normally found embedded in HTML code. That is because JavaScript is run by the
client computer's browser. JavaScript is supported by all internet browsers and was standardized
by the European Computer Manufacturers Association (ECMA). It was standardized under the
name ECMAScript and it is vendor-neutral standard.
The HTML page may contain JavaScript which is run by the browser when the HTML page or other
type of file is loaded.
JavaScript is an object oriented language. Beyond that, it has many similarities to the C
programming language. Variables are declared before use but they are not explicitly typecast. The
variable type is normally determined by its use.
The rest of the functionality of JavaScript is contained in its objects. The objects contain:
1. Methods (Functions)
2. Parameters (Data or Other objects) - Describe characteristics of the object
3. Events - Events are tied to objects
JavaScript has basically three types of objects which are:

Top level objects


18
CK

Web Development Technologies

Objects that are properties of other objects.

Objects that are not properties of other objects


JavaScript objects do not have the normal class to subclass relationship, but are contained within
one another and they do not inherit properties from each other. JavaScript is a tool to allow
manipulation of objects that are already created by the computer system such as "navigator" to
access browser characteristics.
Syntax Rules
Statements may contain a semicolon at the end of them as in C, but it is not necessary
unless there are multiple statements on one line. Multiple statements on one line must be
separated by a semicolon.
JavaScript is case sensitive.
Quotes may be single quote (') or double quote ("). When embedded within each other
they must be used consistently as in the following example.
o onMouseOver="window.status='To Operating Systems Section' ;return true"
Comments are the same as in C++ with the "//" characters for a single line comment, and
the "/*" for the beginning of a multiline comment and the "*/" for the end of a multiline
comment.
Variables must be defined before they are used.

Embedding Script
JavaScript statements are hidden in HTML comments to prevent incorrect interpretation by
older browsers that do not recognize JAVA script. An example HTML document with embedded
JAVA script is shown below.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>An Example of JavaScript code</title>
<head>
<body>
<script language="JavaScript">
<!-- Use the HTML comment to hide JavaScript from old browsers
document.write("This text was written using JavaScript.")
// End hiding JavaScript -->
</script>
<NOSCRIPT>
You see this if your browser won't run JavaScript.
</NOSCRIPT>
</body>
</html>

19
CK

Web Development Technologies


Note that there are two tags used to implement this script example:
i.

SCRIPT - The area between the <SCRIPT> and the </SCRIPT> tags defines the script
program.

Language - Defines the script language. Choices are JavaScript and VBScript.
SRC - Defines an external file containing the source code of the JavaScript. It may
be a URL with the complete path to the script which may reside at another
website. An example is:
<script language="JavaScript" SRC="testscript.js">

ii.

NOSCRIPT - The area between the <NOSCRIPT> and the </NOSCRIPT> tag is run by
browsers that can't run JAVA script or have the feature turned off.

Other Script embedding methods and information


Entities which begin with "&{" and end with "};" Example:
<html>
<head>
<title>The entity method of using JavaScript.</title>
<script language="JavaScript"><!-CGILink="http://www.ctdp.tripod.com/independent/web/cgi/index.html"
// -->
</script>
</head>
<body>
<A HREF="&{CFILink};">Go to CGI Section.</A>
</body>
</html>

Comments are started with "//" for a single line, along with the "/*" to start a comment and
"*/" to end a comment for multiple lines. The comments work the same as in C++.
In JAVA, a variable must be defined before it is used, therefore it is a common practice to
place JavaScript definitions in the header section of an HTML file. The example below will
randomly select and display a greeting in an HTML header of size three.
<HTML>
<HEAD>
<TITLE>Common JavaScript definition practice</TITLE>
<SCRIPT language="JavaScript">

20
CK

Web Development Technologies


<!-Greeting = new Array(4);
Greeting[0] = "have a nice day."
Greeting[1] = "it's a great day."
Greeting[2] = "have a great day!"
// -->
</SCRIPT>
</HEAD>
<BODY>
<CENTER><H1>This is a Greeting Example</H1></CENTER>
<SCRIPT language="JavaScript">
<!-i1 = Math.round(Math.random() * 3)
document.write(("<H3>Hi, " + Greeting[i1] + "</H3>\n")
// -->
</SCRIPT>
</BODY>
</HTML>

Special characters include:


o
o
o
o
o

\b - backspace
\f - Form feed
\n - New line
\r - Carriage return
\t - Tab

JavaScript Operators
Math
Operator

Meaning

Addition

Subtraction

Multiplication

Division

Modulus

++

Increment

Decrement

Negation

Strings are concatenated together using the "+" operator.


Bitwise Operators
21
CK

Web Development Technologies


These operators work at the bit level performing the operator function on a bit per bit basis.
The operation must be thought of as binary, octal, or hexadecimal values (depending on
preference) to consider how it works. Consider the decimal number 15.
15 & 3 = 3 - Equivalent binary: 1111 & 0011 = 0011
15 | 3 = 15 - Equivalent binary: 1111 | 0011 = 1111
15 | 16 = 31 - Equivalent binary: 1111 | 10000 = 11111
15 | 30 = 31 - Equivalent binary: 1111 | 11110 = 11111
Operator

Meaning

&

AND

NOT

OR

exclusive OR

<<

Left shift

>>

Right shift

>>>

Right shift, fill with zeros

Logical Operators
Logical operators operate on boolean values which are either true or false.
Operator
Meaning
&&

AND

||

OR

NOT

Conditional

,
Comma
The syntax for the conditional operator is:

JavaScript Control Statements


This describes the use of JaveScript control statements such as the if statement, while statement,
the for statement, and the switch statement. It provides examples.

if
if (value == 3)
{
document.write("Value is three")
}
22
CK

Web Development Technologies


else
{
document.write("Value is not three")
}

While
var i = 0
while (i < 3)
{
i++
}

Do While
The example prints the days of the week.
days = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var day = 0
do
{
document.write(days[day] + " is day " + eval(day+1) + " of the week.<BR>\n")
day++
} while (day < 7)
For
The following example will determine what numeric day of the week Wednesday falls on.
days = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var day = "Wednesday"
var place
for (i = 0;i < days.length;i++)
{
if (day == days[i])
{
place = i + 1
}
}
document.write(day + " is day " + place + " in the week.<BR>\n")

23
CK

Web Development Technologies


The switch statement
Runs one or more commands based on the value of the expression being evaluated. An example
is:
switch (day) {
case 1:
document.write("Sunday<BR>\n")
break
case 2:
document.write("Monday<BR>\n")
break
case 3:
document.write("Tuesday<BR>\n")
break
case 4:
document.write("Wednesday<BR>\n")
break
case 5:
document.write("Thursday<BR>\n")
break
case 6:
document.write("Friday<BR>\n")
break
case 7:
document.write("Saturday<BR>\n")
break
default:
document.write("Invalid Weekday<BR>\n")
break
}

Break
The break statement may be used to break out of a while, if, switch, dowhile, or for statement.
The break causes program control to fall to the statement following the iterative statement. The
break statement now supports a label which allows the specification of a location for the program
control to jump to. The following code will print "Wednesday is day 4 in the week".
days = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
24
CK

Web Development Technologies


var day = "Wednesday"
var place
for (i = 0;i < days.length;i++)
{
if (day == days[i]) break;
}
place = i + 1
document.write(day + " is day " + place + " in the week.<BR>\n")
Continue
The continue statement does not terminate the loop statement, but allows statements below the
continue statement to be skipped, while the control remains with the looping statement. The loop
is not exited. The example below does not include any ratings values below 5.
ratings = new Array(6,9,8,4,5,7,8,10)
var sum = 0;
var reviews = 0
for (i=0; i < ratings.length; i++)
{
if (ratings[i] < 5) continue
sum += ratings[i];
reviews++;
}
var average = sum/reviews
For in Statement
Executes a loop similar to a for statement that executes for all the properties in an object. The
example below lists all properties and their values for the document object. The document is the
HTML page being displayed.
for (i in document)
{
document.write("Property = " + i + " Value = " + document[i] + "<BR>\n")
}
A few of the properties and their values are:
Property = activeElement Value = [object]
Property = alinkColor Value = #ff0000
Property = all Value = [object]
Property = anchors Value = [object]
Property = applets Value = [object]
Property = bgColor Value = #ffffff
25
CK

Web Development Technologies


Property = body Value = [object]
Property = cookie Value = pageCount=9
Property = defaultCharset Value = iso-8859-1
Property = domain Value =
Property = embeds Value = [object]
Property = fgColor Value = #000000
Property = fileCreatedDate Value = Thursday, September 21, 2000
.
.
With Statement
Eliminates references to the object within the statement by identifying the default object to be
used inside the braces. This example prints out the document properties and values without
referencing the document object to perform the function.
with (document)
{
for (i in this)
{
write("Property = " + i + " Value = " + document[i] + "<BR>\n")
}
}

JavaScript Functions
Defining Functions
JavaScript functions are defined using the key word "function" followed by its name and
variables being passed to it in the following syntax:
function fname(value1,value2, ...)
{
statement1
statement2
.
}
An example:
<HTML>
<HEAD>
<TITLE>A function definition</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hiding JavaScript
26
CK

Web Development Technologies


function listItems(itemList)
{
document.write("<UL>\n")
for (i = 0;i < itemList.length;i++)
{
document.write("<LI>" + itemList[i] + "\n")
}
document.write("</UL>\n")
}
// End hiding JavaScript -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!-days = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
listItems(days)
// -->
</SCRIPT>
</BODY>
</HTML>

Calling Functions
If evaluate() is a defined function, the following line will call the function:
<SCRIPT LANGUAGE="JavaScript">
<!-i3 = evaluate (Tree)
// -->
</SCRIPT>
This function may evaluate the members of the array tree to see how many match a certain
criteria.
Another way to call a function is to tie it to an anchor:
<A HREF="javascript:redirectLink()">redirecting</A>
Another way is to tie it to an event:
<A NAME="javatest" onClick="redirectLink()">redirecting</A>
27
CK

Web Development Technologies


This will cause the redirectLink() function to run when the text "redirecting" is clicked on. The
text inside the anchor reference is not marked as a link, nor does the mouse change when placed
over the text. This is one way to make truly invisible links, that no one would know had any
function until they click on it.
Functions Properties
Functions in JavaScript is actually an object. Therefore any created function created using the
"function" declaration will have the properties of a function. These properties are:

Arguments - An array of arguments passed to the function. This is an array object which
has a property of length which enables the programmer to tell how many arguments (or
variables) are passed to the function.
Caller - The name of the function that called the function.
Prototype - Used to make more properties.

Using the Arguments Array


The arguments array is a member of every function. It can be used to determine how many
variables are being passed to the function, and what they are, without each argument being
explicitly declared in the function. The following example performs the same task as the above
example:
function listItems()
{
var items = listItems.arguments.length
document.write("<UL>\n")
for (i = 0;i < items;i++)
{
document.write("<LI>" + listItems.arguments[i] + "\n")
}
document.write("</UL>\n")
}
The function may be called as follows:
listItems("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Happyda
y")
Local variables
Local variables may be defined inside functions. The following example uses the variables, sum
and items as local variables.
function average()
{
28
CK

Web Development Technologies


var items = average.arguments.length
var sum = 0
for (i = 0; i < items;i++)
{
sum += average.arguments[i]
}
return (sum/items)
}
document.write(average(6,9,8,4,5,7,8,10))
Return
As in the example above, the return statement will return a value to the statement that invoked
the function. In the above example, the average value is written to the document. The return
statement will return the value as float, string, integer or whatever is appropriate for use.

JavaScript Form Input


This section describes how to pre-process form input for accuracy before submitting the
information to the server.
The Form Code
<H1 Align=Center>Computer Technology Documentation Project</H1>
<H2 Align=Center>Member Registration</H2>
<HR SIZE=5 WIDTH=90%>
<TABLE>
<TD>
</TD>
<TD>
<PRE>
<FORM NAME="RegistrationForm">
<B>First Name: </B><INPUT TYPE=TEXT NAME="firstname">
<B>Last Name:
</B><INPUT TYPE=TEXT NAME="lastname">
<B>Address1:
</B><INPUT TYPE=TEXT NAME="addr1">
<B>Address2:
</B><INPUT TYPE=TEXT NAME="addr2">
<B>City:
</B><INPUT TYPE=TEXT NAME="city">
29
CK

Web Development Technologies


<B>State:

</B><SELECT NAME="state" SIZE=0>


<OPTION VALUE="0">-<OPTION VALUE="1">AL
<OPTION VALUE="2">AK
<OPTION VALUE="3">AR
<OPTION VALUE="4">AS
<OPTION VALUE="5">AZ
<OPTION VALUE="6">CA
<OPTION VALUE="7">CO
<OPTION VALUE="8">CT
<OPTION VALUE="9">DC
<OPTION VALUE="10">DE
<OPTION VALUE="11">FL
<OPTION VALUE="12">FM
<OPTION VALUE="13">GA
<OPTION VALUE="14">GU
<OPTION VALUE="15">HI
<OPTION VALUE="16">ID
<OPTION VALUE="17">IA
<OPTION VALUE="18">IL
<OPTION VALUE="19">IN
<OPTION VALUE="20">KS
<OPTION VALUE="21">KY
<OPTION VALUE="22">LA
<OPTION VALUE="23">MA
<OPTION VALUE="24">MD
<OPTION VALUE="25">ME
<OPTION VALUE="26">MH
<OPTION VALUE="26">MI
<OPTION VALUE="28">MN
<OPTION VALUE="29">MO
<OPTION VALUE="30">MP
<OPTION VALUE="31">MS
<OPTION VALUE="32">MT
<OPTION VALUE="33">NC
<OPTION VALUE="34">ND
<OPTION VALUE="35">NE
<OPTION VALUE="36">NH
<OPTION VALUE="37">NJ
<OPTION VALUE="38">NM
<OPTION VALUE="39">NV
<OPTION VALUE="40">NY
<OPTION VALUE="41">OH
<OPTION VALUE="42">OK
30
CK

Web Development Technologies


<OPTION VALUE="43">OR
<OPTION VALUE="44">PA
<OPTION VALUE="45">PR
<OPTION VALUE="46">PW
<OPTION VALUE="47">RI
<OPTION VALUE="48">SC
<OPTION VALUE="49">SD
<OPTION VALUE="50">TN
<OPTION VALUE="51">TX
<OPTION VALUE="52">UT
<OPTION VALUE="53">VA
<OPTION VALUE="54">VI
<OPTION VALUE="55">VT
<OPTION VALUE="56">WA
<OPTION VALUE="57">WI
<OPTION VALUE="58">WV
<OPTION VALUE="59">WY
</SELECT>
<B>Zip:
</B><INPUT TYPE=TEXT NAME="zip" MAXLENGTH=10 SIZE=10>
<B>Area Code/Phone:</B><INPUT TYPE=TEXT NAME="code" MAXLENGTH=3 SIZE=3>
<INPUT TYPE=TEXT NAME="phone" MAXLENGTH=7 SIZE=7>

<INPUT TYPE="BUTTON" NAME="cmdSubmit" VALUE="Submit"> <INPUT TYPE="RESET"


VALUE="Clear">
</PRE>
</FORM>
</TD>
</TABLE>
What the Working Form Looks Like:
Computer Technology Documentation Project
Member Registration

First Name:
Last Name:
Address1:
31
CK

Web Development Technologies


Address2:
City:
State:

Zip:
Area Code/Phone:

The Script
This is placed in the HTML header:
<SCRIPT SCRIPT FOR="cmdSubmit" EVENT="onclick" LANGUAGE="JavaScript">
<!-var TheForm;
TheForm = document.RegistrationForm;
if (TheForm.firstname.value.length == 0) {
alert("Please enter your first name.");
TheForm.firstname.focus();
}
else if (TheForm.lastname.value.length == 0) {
TheForm.lastname.value = prompt("Please enter your last name.");
if (TheForm.lastname.value.length != 0)
TheForm.addr1.focus();
}
else if (TheForm.addr1.value.length == 0) {
alert("Please enter your address.");
TheForm.addr1.focus();
}
else if (TheForm.city.value.length == 0) {
alert("Please enter the city.");
TheForm.city.focus();
32
CK

Web Development Technologies


}
else if (TheForm.state.value.length != 2) {
alert("Please enter the 2-letter state abbreviation.");
TheForm.state.focus();
}
else if (TheForm.zip.value.length < 5) {
alert("Please enter a valid zip code.");
TheForm.zip.focus();
}
else if (TheForm.code.value.length != 3 ||
isNaN(TheForm.code.value)) {
alert("Please enter a valid area code.");
TheForm.code.focus();
TheForm.code.select(
);
}
else if (TheForm.phone.value.length != 7 ||
isNaN(TheForm.phone.value)) {
alert("Please enter a valid phone number.");
TheForm.phone.focus();
TheForm.phone.select();
}
// -->
</SCRIPT>
Invoking the Script
The script is invoked when the user clicks on the Submit button. Try it in the above form.

33
CK

Вам также может понравиться