1 lecture #6 dynamic web documents hait summer 2005 shimrit tzur-david
TRANSCRIPT
2
Client-Server Architecture
• In a client-server architecture, computation is done either in the client or in the server
• There are cases where we can choose whether to perform the computation in the client or in the server
• There are cases where we cannot choose where to perform the computation– For example, accessing a database
3
Form Validation
• Consider the case where a user is required submit his name to a server application
• Where, for example, should we check that the inserted value is not an empty string?– In the client (i.e., the Web browser)?– In the server?
4
Client Side Technologies
• Javascript– Developed by Netscape
– Supported by all browsers (although not all support the standard)
– Very light (no graphics) and good interaction with HTML
• Java Applets– Developed by Sun
– In the past it was supported by all browsers, but not any more
– Capable of doing almost anything that Java allows
5
JavaScript Overview
• A "scripting" language for HTML pages
• The code is embed in HTML pages
• The browser interprets and executes the script (it is not compiled)
• Do not declare data types for variables (loose typing)
• Dynamic binding – object references checked at runtime
6
Overview – Cont.
• Scripts can manipulate "browser objects:"– HTML form elements– Images– Frames– etc.
• For security – cannot write to disk (when run on a client)
7
Abilities
• Generating HTML content dynamically
• Monitoring and responding to user events
• Validate forms before submission
• Interact with the frames and windows of the browser
• Customize pages to suit users
8
Example
<HTML><HEAD><TITLE>An Hello World Example</TITLE><SCRIPT LANGUAGE = "JavaScript"> document.write("<font size='+4'>"); document.writeln("Hello World!<br>"); document.writeln("What a boring example</font>") </SCRIPT></HEAD><BODY> <!-- An empty document body --> </BODY></HTML>
Why do we need <br> if we used writeln?
10
Example 2
<HTML><HEAD><TITLE>An Hello World Example</TITLE><SCRIPT LANGUAGE = "JavaScript"> document.write("<font size='+4'>"); document.writeln("Hello World!<br>"); document.writeln("What a boring example</font>") </SCRIPT></HEAD><BODY> <h1>My Hello World Example</h1> </BODY></HTML>
12
Example 3
<HTML><HEAD><TITLE>An Hello World Example</TITLE><SCRIPT LANGUAGE = "JavaScript"> document.write("<font size='+4'>"); document.writeln("Hello World!<br></font>");</SCRIPT></HEAD><BODY> <h1>My Hello World Example</h1> <SCRIPT LANGUAGE = "JavaScript"> document.writeln("What a boring example")</SCRIPT></BODY></HTML>
14
JavaScript Variables
• Untyped!
• Can be declared with var keyword:var foo;
• Can be created automatically by assigning a value:val = 1;
val = “Thank for all the fish";
val has changed from an int to a String!
15
Variables Names
• A variable name can be any valid identifier• The identifier is a series of characters
– Consisting of letters (lower and upper case), digits, and underscores (_)
– Does not begin with a digit– Does not contain any space
• Javascript is case sensitive (foo and FOO are different)
16
Variables
• Local variable is available only in the function where it is declared
• Global variable is available all over the document
• A variable declaration – Inside a function creates a local variable– Outside a function creates a global variable
• Local variables must be declared with var
17
Literals
• The typical bunch:– Numbers 17 123.45– Strings “Let it be”– Boolean: true false– Arrays: [1,“ab ba”,17.234]– null– undefined
Arrays can hold anything!
18
Operators
• Arithmetic, comparison, assignment, bit wise, Boolean (pretty much just like Java)
+ - * / % ++ --
== != > < >= <=
&& || ! & | << >>
+= -= *= /= %=
19
The Special Plus Command
• Which of the following two is correct?
• What is the ‘type’ of the answer?
x = “The answer is” + 42y = 42 + “is the answer”
String
20
Which is correct?
• Which of the following two is correct?
• What is the ‘type’ of the answer?
x = "37" + 7y = "37" - 7
String, output: 377
Number, output: 30
21
Types of Equality
• The equals == checks if both operands are equal after performing type conversion
• The equals === checks if both operands are of the same type and equal
• Example:– Is 3 == "3" (true or false?)– Is 3 === "3" (true or false?)
true
false
22
Conditional Operators
• equalsif (a == b) {…}
• not equalsif (a != b) {…}
• greater than or equal toif (a >= b) {...}
• less than or equal toif (a <= b) {...}
24
<HTML><HEAD><TITLE>Using Variables</TITLE><SCRIPT LANGUAGE = "JavaScript">
var firstNumber = 11, secondNumber = 23, sum;sum = firstNumber + secondNumber;document.write("<FONT COLOR = 'blue' SIZE = '6'>The sum of " + firstNumber + " and " + secondNumber + " is </FONT>");document.write(" <FONT COLOR = ‘red' SIZE = '7'>" + sum + "</FONT>");
</SCRIPT></HEAD><BODY> <!-- An empty document body --> </BODY></HTML>
26
JavaScript Constructs
• condition (selection)if (condition) {statements if true}
else {statements if false}
if (metushelahAge < yourAverageAge) { document.write ("<body><h2>its true that Metushelah is younger than most of you,") document.write ("<br>computers never lie!</h2>
</body>")
}
27
JavaScript Constructs
• loop (iteration): both for and while loops are available
for (var i=0; i < myform.myAge.value.length; i++) {var oneChar=myform.myAge.value.substring (i, i+1)
if (oneChar < "0" || oneChar > "9") {alert("Please enter a valid number "
+ oneChar + " is not valid.")}
}
28
<HTML><HEAD><TITLE>Loops Example</TITLE><SCRIPT LANGUAGE = "JavaScript">
for (var counter = 1 ; counter <= 8 ; ++counter) { document.write(“<P><FONT COLOR = ‘blue’ SIZE = ‘ “ + counter + “ '> Now with font size " + counter + " </FONT></P> “);
}</SCRIPT></HEAD><BODY> <!-- An empty document body --> </BODY></HTML>
30
JavaScript Functions
• Functions are first class citizens
• The keyword function used to define a function (subroutine):
function add(x,y) {
return(x+y);
}
31
Function Input and Output
• Numbers and Boolean values always passed to functions using call-by-value
• For objects, a call-by-reference is used to pass them to the functions
• Numbers and Boolean values are always returned by value
• Objects returned by reference
32
Example
• The next example uses functions to computing the Fibonacci numbers
• Note the use of recursion
• Be careful, some browsers may not deal well with very big numbers in the input (i.e., too many recursive calls)
33
<HTML><HEAD><TITLE>Functions Example</TITLE><SCRIPT LANGUAGE = "JavaScript">function fibonacciValue() { var value =
parseInt(document.fibonacciForm.number.value ); window.status = "Calculating Fibonacci number for " +
value; document.fibonacciForm.result.value = fibonacci(value); window.status = "Done Calculating Fibonacci number";}function fibonacci( n ) { if (n == 0 || n == 1) return n; else return fibonacci( n - 1 ) + fibonacci( n - 2 );}</SCRIPT></HEAD>
34
<BODY> <FORM NAME = "fibonacciForm"><TABLE BORDER = "1" BGCOLOR = “fabbfc">
<TR><TD BGCOLOR = “eabbfc">Enter a number</TD> <TD><INPUT NAME = "number" TYPE = "text"></TD>
<TD><INPUT TYPE = "button" VALUE = "Calculate" ONCLICK = "fibonacciValue()"</TR>
<TR><TD BGCOLOR = “fabbfc">Fibonacci Value</TD> <TD><INPUT NAME = "result" TYPE = "text"> </TD> </TR>
</TABLE></FORM></BODY></HTML>
35
Function Arguments
• Within a function, its arguments can be accessed with arguments[i].
• The number of arguments is arguments.length
• A function can be created that takes any number of arguments
36
Example
function myConcat(separator) { result="" // initialize //What does this return? list // iterate through arguments for (var i=1; i<arguments.length; i++) { result += arguments[i] + separator } return result}
myConcat(“%","red","orange","blue")
red%orange%blue
37
Objects
• Objects have attributes and methods
• There are pre-defined objects and user-defined object types
• Using objects has similarity to the syntax of C/Java:
objectName.attributeName
objectName.methodName()
objectName.attributeName
objectName.methodName()
38
Objects Are Like Arrays
myCar.make = "Ford"myCar.model = "Mustang"myCar.year = 66;
myCar[“make”] = "Ford"
myCar[“model”] = "Mustang"
myCar[“year”] = 66;
39
function show_props(obj, obj_name) { var result = "" for (var i in obj) result += obj_name + "." + i +
" = " + obj[i] + "\n" return result}
myCar.make = FordmyCar.model = MustangmyCar.year = 66
So, the function call show_props(myCar, "myCar")would return the following:
40
Creating a New Object
• There are two ways to create new objects:
• Object Initializer:– objectName={prop1:val1, …, propN:valN}
• Constructor Function:– define a constructor function– create the new object using new
41
Examplefunction car(make, model, year) { this.make = make this.model = model this.year = year}
theMazda = new car(“Mazda", “323", 1991)theHonda = {make:”Honda”, year:1992, color:"red",wheels:4,
engine:{cylinders:4,size:2.2}}
42
Creating a Method
• A method of an object is a function that has been assigned to the object:
object.methodName = functionName