Browser Scripting Java Script 1 Introduction 2 ClientServer
Browser Scripting Java. Script 1
Introduction 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 - For example, validating forms • There are cases where we cannot choose where to perform the computation - For example, accessing a database 3
Client Side Technologies • Java. Script - Developed by Netscape, standardized by ECMA - Supported by all browsers (although not all support the standard) • VBScript - Developed by Microsoft - Supported only by Microsoft Internet Explorer - A light version of Microsoft Visual Basic • Java Applets - Developed by Sun 4
About Applets • An applet is a Java class that runs in a frame that is embedded in a Web page <object type="application/x-java-applet" classid="my. Applet. class" width="x" height="y"> • When a browser loads the Web page, the applet bytecode (. class file) is downloaded to the client box and executed by the browser • Commonly used for games, graphics, etc. 5
6
Browser Scripting • Browser scripts are procedural programs embedded inside HTML <script type="text/javascript">script</script> <script type="text/vbscript">script</script> • Can read and manipulate HTML elements, CSS properties, and the browser itself 7
Web Architecture for Scripts Client Server Web browser HTML Page: <SCRIPT> …code. . … </SCRIPT> built-in Script interpreter HTML/HTTP TCP/IP Internet HTML/HTTP TCP/IP Web (HTTP) Server HTML pages with embedded script 8
Why are Scripts Needed? • Generating HTML content dynamically • Monitoring and responding to user events • Validating forms before submission • Manipulating HTTP cookies • Interaction among the frames and windows of the browser 9
Java. Script History • Introduced in Netscape 2 (1996) • Standardized by ECMA under the name ECMAScript (1997 -1999) • The latest version is ECMAScript 3, and it is equivalent to Java. Script 1. 5 10
Java. Script Basics 11
Java. Script is NOT Java! • Java. Script is not compiled • Java. Script is typically executed by Web browsers and not as stand-alone applications • Java. Script and Java have some similarity in syntax • The choice of the name is mainly for historical reasons 12
Dynamic HTML Content: Example 1 <html> <head><title>JS Example</title></head> <body> <h 2>Before the script</h 2> <script type="text/javascript"> document. write('<h 1>In the script</h 1>') </script> <h 2>After the script</h 2> </body></html> 13
14
Dynamic HTML Content: Example 2 <html> <head><title>JS Example</title></head><body> <h 2>Before the script</h 2><h 1> <script type="text/javascript"> document. write(new Date(). to. Locale. String()) </script> </h 1><h 2>After the script</h 2> </body></html> 15
Dynamic HTML Content: Example 3 <h 2>Hello and <i><script type="text/javascript"> hours = new Date(). get. Hours(); if (hours < 10) { document. write("good morning") } else {document. write("good day") } </script></i>. </h 2> 16
Basic Constructs • Statement blocks var x=5 document. write(x); var x=5, y=7; document. write(x+y); - Semicolon (; ) is optional at end of line • Conditions: if, if-else, ? : , switch if (condition) {statements if true} x= (y>0)? y: 0 else {statements if false} • Loops: for, while, do-while (condition) {statements} 17
Variables • Java. Script variables are not typed! (but values are) - var x = 5; x="abcd"; . . . • Thus, the value of a variable is characterized by both value and type • Variables are declared with var keyword: - var x; var y=5; • A variable name consists of letters, digits, and underscores (_), and does not begin with a digit 18
Data Types • Values have one the following types: - number: 5, 2. 3, 0 x. FF, 6. 67 e-11 - object: new Date() • Arrays: [1, "ab ba", 17. 234] • null - string: "Hello World" - boolean: true, false You can use typeof(x) - undefined: no value assigned. . . to get the type of x: number, string, object. . . 19
Some of the Reserved Words typeof abstract do public if as in return implements use var break instanceof else import void case interface export static while catch is extends super with class namespace false switch const new final this continue null finally throw default package for true delete private function try 20
Operators • Arithmetic: + ++ - -- * / % • Comparison: == != === !== > >= < <= • Logical: & && | || ! • Bitwise: & | ^ ~ << >> >>> • String: + • Assignments: = += -= *= /= <<= |=. . . 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 34 == "34" ? Is 34 == "3"+"4" ? - Is 34 === "3"+"4" ? Is 34 !== "3"+"4" ? 22
An Example <script type="text/javascript"> for (var counter = 1 ; counter <= 8 ; ++counter) { var fontsize = counter + 10; fontsize+="pt"; document. write("<p style='font-size: "+fontsize+"'>" + "Font size " + fontsize + " </p>"); } </script> 23
24
Functions 25
Functions • Java. Script functions are special objects with operator () • Syntax: function fname(args. . . ) {statements} • Usually, functions are defined at the head of the file - Why? • Some functions are predefined - For example, parse. Int(string) • Functions can return values 26
Function Example <html> <head> <script type="text/javascript"> function add(x, y) { return x+y; } </script> </head> <body> <h 1> <script type="text/javascript"> sum = add(4, 5); document. write("4+5="+sum); </script> </h 1> </body> </html> 27
Function Values • Numbers and Booleans are passed to functions by value • Objects and strings are passed to functions by reference • Numbers and Boolean values are always returned by value • Objects and strings are returned by reference 28
Undeclared Arguments • Function may receive arguments without declaring them • Within a function, its arguments are held in the arguments array - can be accessed with arguments[i] - The number of arguments is arguments. length • Hence, it is possible to define functions that take any number of arguments 29
An Example What is the result of the following code? function my. Concat(separator) { var result=""; // iterate through arguments for (var i=1; i<arguments. length; i++) { result += arguments[i] + separator; } return result; } con = my. Concat(", ", "red", "orange", "blue"); 30
Predefined Functions • Java. Script include several predefined functions • For example, - eval(code-string) – gets a string of Java. Script code, evaluates it and executes it • It allows dynamic code execution - parse. Int(string) – takes a string argument and converts its beginning to an integer (or return Na. N) 31
Variable Scopes • Java. Script variables are recognized inside their declaration scope • Hence, global variables should be declared outside the functions • A variable declared in a function can also be global, if var is omitted - However, avoid this bad style. . . 32
Objects and Arrays 33
Object Model • Java. Script objects are similar to associative arrays • That is, an object associates identifiers (e. g. , first. Name) with values (attributes) (e. g. , "John") • Those values may be other objects (nested objects) • Those values can also be functions (methods) - e. g. , function set. Person. Age(age) {this. age = age} • When o. f() is invoked, o can be referred to as this 34
Creating Objects • Objects can be created in several ways: • Object initializers var the. Nissan = {make: "Nissan", year: 2003, color: "blue"} • Object assignments the. Mazda = { make: "Nissan" } the. Mazda. year = 2002; the. Mazda. color="black"; 35
Creating Objects (cont( • Object Constructors - define a constructor function - create the new object using new function car(make, year, color) { this. make = make this. year = year this. color = color } the. Honda = new car("Honda", 2001, "green") 36
Defining Methods • Methods are associated with objects just like attributes function nice. String() { return "<span style='color: "+ this. color + "'>" + this. make + " "+ this. year + "</span>" } the. Nissan = {make: "Nissan", year: 2003, color: "blue", str: nice. String} 37
Defining Methods (cont( the. Nissan = {make: "Nissan", year: 2003, color: "blue"} the. Nissan. str = nice. String; function car(make, year, color) { this. make = make this. year = year this. color = color this. str = nice. String } the. Honda = new car("Honda", 2001, "green") 38
Accessing Object Properties • Object attributes can be accessed in several ways: - object. att. Name - object["att. Name"] • Thus, object methods are invoked in Java/C++ style: - object. method(arguments) • Alternatively: - object["method"](arguments) 39
The Complete Example function nice. String() { return "<span style='color: "+ this. color + "'>" + this. make + " "+ this. year + "</span>" } function car(make, year, color) { this. make = make; this. year = year; this. color = color; this. str = nice. String } var the. Honda = new car("Honda", 2001, "green"); document. write(the. Honda. str()); 40
Array Objects • Arrays are supported as objects • Attribute length • Methods include: concat, join, pop, push, reverse, sort, shift, . . . • Arrays can be passed to functions as arguments • The array is passed by-reference 41
Creating Arrays • var a = ["red", "blue", "green"] - Allocates an array of 3 cells and initializes the values • var b = new Array(5) - Allocates an array of 5 cells without initializing values • var c = new Array() - Creates a new empty array 42
Array Elements • Array elements need not have the same type - arr 1 = ["hello", 1, true] • Java-like access: arr[i] • Array indices need not be contiguous - arr 1[10] = 66 • Multi-dimensional arrays are arrays of arrays - var matrix = [ [0, 1, 1], [1, 1, 0], [0, 0, 0]] 43
Miscellaneous 44
Java. Script and XHTML Strict • Embedding Java. Script code inside XHTML may violate XML rules - e. g. , x<5 && x>2 • One solution is to import Java. Script code from external files, e. g. : <script type=". . . " src="jsfile. js"/> - Always a good habit. . . • Another solution: wrap the code in an XML CDATA section 45
Wrapping Code in CDATA <script type="text/javascript"/> //<![CDATA[ regular Java. Script code. . . //]]> </script> 46
The String Object • Java. Script has a built-in String object - not the primitive string! • Create a String object from a string primitive: - my. String = new String("This is a string object") • Extract the primitive string from a String object: - str = my. String. value. Of() 47
String Common Methods • char. At (index) • split(string) • char. Code. At(index) • substr(start, length) • concat(string) • substring(start, end) • from. Char. Code(value 1, value 2, …) • • • index. Of(substring, index) • • last. Index. Of(substring, index) • • slice(start, end) to. Lower. Case() to. Upper. Case() value. Of() match(regexp) 48
An Example - Format Verification • What does the following function do? function get. String() { var result = null; while(result==null) { var answer = prompt("Your first name: ") if(answer!=null) { result = new String(answer); result = result. to. Lower. Case(). match("^[a-z]+$"); } if(result==null) { alert("Don't mess with me!") } } return answer } 49
The Math Object • The object Math is used for mathematical operations - E. g. , Math. pow(x, 2) • Other useful functions: • abs(x) • cos(x) • pow(x, y) • round(x) • sin(x) • sqrt(x) • ceil(x) • tan(x) • log(x) • floor(x) • exp(x) • max(x, y) • min(x, y) • Math Also includes constants such as: Math. E, Math. PI 50
The with Statement • Establishes the default object for a set of statements • Within the set of statements, any property references that do not specify an object are assumed to be of the default object var a, x, y var r=10 with (Math) { a = PI * r; x = r * cos(PI); y = r * sin(PI/2) } 51
The Date Object • Create the current date: new Date() • Create an arbitrary date: new Date(date-string) • Common methods of Date: • get. Date() • get. Hours() • get. Full. Year() • get. Minutes() • get. Month() • get. Seconds() • get. Day • get. Milliseconds() • get. Time() • to. Locale. String() 52
- Slides: 52