Lect03

  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Lect03 as PDF for free.

More details

  • Words: 10,818
  • Pages: 109
The Basic of JavaScript

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

1

The JavaScript Language `

`

`

Originally, developed by Netscape for both client-side Originally client side and server-side scripting as LiveScript. Became a joint venture of Netscape and Sun in 1995, renamed JavaScript

Technically its name is ECMA-262 (also ISO 16262), which refers to the international standard which defines it it. ◦ ECMA-262 edition 3 is the current standard x Edition 4 is under development

`

`

The standard is derived mostly from Netscape's JavaScript, but it does have some features from Microsoft's JScript.

Its most common use (by (b ffar)) is to provide d scripting support for Web browsers. All of the popular "modern" Web browsers support the core standard. SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

2

JavaScript/EcmaScript References `

The official EcmaScript EcmaScript, third edition edition, specification

◦ http://www http://www.ecmaecmainternational.org/publications/files/ECMAST/Ecma-262.pdf

`

A working version of the 4thh edition of the EcmaScript language specification

◦ http://www.carsoncheng.com/Ecma/tc39-tg1-2006001.pdf

`

JavaScript as implemented in Mozilla products ◦ http://developer.mozilla.org/en/docs/JavaScript

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

3

JavaScript Components `

Core

◦ The heart of the language

`

Client-side

◦ Library of objects supporting browser control and user interaction use te act o

`

Server-side

◦ Library y of objects j that support pp use in web servers

`

This class focuses on client-side

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

4

Object-Orientation Object Orientation and JavaScript ` `

We ll call collections of JavaScript code scripts We’ll scripts, not programs. JavaScript and Java are only related through syntax. ◦ JavaScript is dynamically typed. ◦ JavaScript’s S ’ support ffor objects b is very d different. ff

`

JavaScript is object-based but NOT a true objectoriented programming language ◦ Does not support class-based inheritance ◦ Cannot support polymorphism ◦ Has prototype-based inheritance, which is much different

See http://en.wikipedia.org/wiki/Prototype-based_languages http://en wikipedia org/wiki/Prototype based languages x See, SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

5

JavaScript Objects ` `

`

`

`

Objects are collections of properties Properties are either data properties or

method properties

Data properties are either primitive values or references to other objects Primitive values are often implemented directly in hardware The Object object is the ancestor of all objects in a JavaScript program ◦ Object has no data properties, but several method properties

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

6

Java and JavaScript `

Java 1.6 1 6 has support for scripting

◦ http://java.sun.com/javase/6/docs/technotes/guid es/scripting/index html es/scripting/index.html

`

Mozilla Rhino is an implementation of JavaScript in Java ◦ http://www.mozilla.org/rhino/

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

7

Uses of JavaScript `

Provide alternative to server server-side side programming ◦ Servers are often overloaded ◦ Client processing has quicker reaction time

`

`

` `

JavaScript can be used to replace some of what is typically done with applets (except graphics) JavaScript can be used to replace some of what is done with CGI (but no file operations or networking) JavaScript can work with forms JavaScript can interact with the internal model of the web page (Document Object Model)

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

8

Uses of JavaScript `

(continued)

Event-Driven Event Driven Computation

◦ User interactions with HTML documents in x JavaScript use the event-driven model of computation x User interactions with form elements can be used to trigger execution of scripts

`

JJavaScript S i t is i used d tto provide id more complex l user interface than plain forms with HTML/CSS can provide ◦ http://www.protopage.com/ is an interesting example ◦ A number of toolkits are available. Dojo, found at http://dojotoolkit.org/, is one example

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

9

Embedding JavaScript in a Web Page `

`

`

` `

Code C d ffor defining d fi i ffunctions i or creating i d data structures are placed in <script> elements inside the page’s element. Code for generating HTML to be displayed as part of the page are placed for <script> elements inside the where the g generated HTML code will be inserted. Code for actions triggered by events are given as values for event attributes of HTML tags. (Examples of event attributes are onfocus, onfocus onblur, onblur onclick, onclick onmouseover, onmouseover and onmouseout) Place code in a separated file and call from <script> elements JavaScript statements are executed in document order as the Web page is first being loaded into the browser. SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

10

JavaScript in XHTML `

Directly embedded <script type=“text/javascript”> ◦ However, note that a-- will not be allowed here!

`

Indirect reference

<script type=“text/javascript” src=“tst_number.js”/> ◦ This is the preferred approach SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

11

JavaScript in XHTML: CDATA `

`

`

The block is intended to hold data that should not be interpreted as XHTML Using g this should allow any y data (including g special p symbols ‘<‘, ‘&’ and ‘--’) to be included in the script This, however does not work, at least in Firefox: <script type=“text/javascript”> //"); ]]> //]]>

`

The problem seems to be that the CDATA tag causes an internal JavaScript error SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

12

JavaScript in XHTML `

This does work in Firefox <script type=“text/javascript”> /* ]] */ /

`

`

The comment symbols y do not bother the XML parser (only /* and */ are ‘visible’ to it) The comment symbols y p protect the CDATA markers from the JavaScript parser

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

13

Example I: firstprogram.html

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

14

Example II: fragmentedscript.html

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

15

General Syntactic Characteristics `

Identifier form: ◦ Start with $, _, letter ◦ Continue with $, _, letter or digit g ◦ Case sensitive

`

25 reserved words, plus future reserved words

`

Comments: both // and /* … */ SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

16

Statement Syntax ` `

`

Statements can be terminated with a semicolon However, the interpreter will insert the semicolon if missing g at the end of a line and the statement seems to be complete Can be a problem: return x;

`

`

If a statement must be continued to a new line, line make sure that the first line does not make a complete statement by y itself Example hello.html

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

17

Primitive Types `

Five primitive types ◦ ◦ ◦ ◦ ◦

`

Number String Boolean – true or false Undefined N ll Null

There are five classes corresponding to the five primitive types ◦ Wrapper objects for primitive values ◦ Place for methods and properties relevant to the primitive types ◦ Primitive values are coerced to the wrapper class as necessary and vice vice-versa necessary, versa SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

18

Primitives and Objects

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

19

Numeric and String Literals `

Number values are represented internally as doubledouble precision floating-point values ◦ Number literals can be either integer or float ◦ Float values may have a decimal and/or and exponent

`

A String literal is delimited by either single or double quotes t

◦ There is no difference between single and double quotes ◦ Certain characters may be escaped in strings x \’ or \” to use a quote in a string delimited by the same quotes x \\ to use a literal li lb backspace k

◦ The empty string ‘’ or “” has no characters

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

20

Other Primitive Types `

Null

◦ A single value, null

◦ null is a reserved word

◦ A variable that is used but has not been declared nor been assigned a value has a null value ◦ Using a null ll value l usually ll causes an error

`

Undefined

◦ A single value value, undefined ◦ However, undefined is not, itself, a reserved word g ◦ The value of a variable that is declared but not assigned a value

`

Boolean

T l d ffalse l ◦ Two values: true and SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

21

Variables `

`

JavaScript is dynamically typed – any variable can be used for anything (primitive value or reference to any object) JavaScript is loosely typed, which means a variable can hold any of JavaScript's JavaScript s literal types:

◦ The interpreter determines the type of a particular occurrence of a variable var x=3.14; x="a string"; x=true;

// number // string // Boolean

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

22

Variables `

`

(continued)

The keyword y var is used to declare variables since no typing is required. Variables can be either implicitly p y or explicitly p y declared

◦ There are some special fixed literal values. It's better to assign predefined literals when weird things happen than to crash Web browsers! var y;

// uninitialized variables are assigned // the literal undefined

var y ="yi"*"kes";

// y contains NaN

t a N b // N Not Number y = 3/0;

// y contains the literal Infinity

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

23

Numeric Operators ` `

The basic syntax is very similar to that of Java and C++ Standard arithmetic

◦+

`

*

-

/

%

Increment and decrement

◦ --

++

◦ Increment and decrement differ in effect when used before and after a variable ◦ Assume that a has the value 3, initially ◦ (++a) * 3 has the value 24

◦ (a++) ( ) * 3 has h the h value l 27 2

◦ a has the final value 8 in either case

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

24

Precedence of Operators Operators ++, --, unary -

Associativity Right

/ % *, /,

Left

+, -

Left

>, <, > >= ,< ,<=

Left

==, !=

Left

, ===,!==

Left

&&

Left

||

Left

=, +=, -=, *=, /=, &&=, ||=, %=

Right

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

25

Assignment Statements ` `

Plain assignment indicated by = Compound assignment with ◦ +=

`

-= =

/=

*=

%=



a += 7 means the same as a = a + 7

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

26

Conditionals and Loops p `

Conditionals are standard:

`

Loops are standard:

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

27

Control Statements `

A compound statement in JavaScript is a sequence of 0 or more statements enclosed in curly braces

◦ Compound statements can be used as components of control statements allowing g multiple p statements to be used where, syntactically, a single statement is specified

`

A controll construct is a controll statement including the statements or compound statements that h it i contains i

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

28

Control Expressions `

A control expression has a Boolean value

◦ An expression with a non-Boolean value used in a control statement will have its value converted to Boolean automatically

`

Comparison operators ◦ ◦ ◦ ◦

`

== != < <= > >= === compares identity of values or objects 3 == ‘3’ is true due to automatic conversion 3 === ‘3’ 3 is false

Boolean operators ◦ &&

`

||

!

Warning! A Boolean object evaluates as true ◦ Unless the object is null or undefined

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

29

Selection Statements `

The if-then and if-then-else are similar to that in other programming languages, especially C/C++/Java

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

30

switch Statement Syntax switch (expression) { case value_1: value 1: // statement(s) case value_2: _ // statement(s) ... [default: // statement(s)] }

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

31

switch Statement Semantics ` `

`

`

`

The expression is evaluated The value of the expressions is compared to the value in each case in turn If no case matches, execution begins at the default case Otherwise, execution continues with the statement following the case Execution continues until either the end of the switch is encountered or a break b k statement is executed Æ SHOW borders2.html SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

32

Loop Statements `

`

`

`

Loop statements in JavaScript are similar to those in C/C++/Java While while (control expression) statement or compound statement For for (initial expression; control expression; increment expression) statement or compound statement do/while do statement or compound statement while (control expression) Æ SHOW date.html SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

33

while Statement Semantics ` `

`

`

The control expression is evaluated If the control expression is true, then the statement is executed These two steps are repeated until the control expression becomes false At that point the while statement is finished

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

34

for Statement Semantics ` ` `

` `

`

The initial expression is evaluated The control expression is evaluated If the control expression is true, true the statement is executed Th th Then the increment i t expression i is i evaluated l t d The previous three steps are repeated as long as the th control t l expression i remains i true t When the control expression becomes false, the h statement is i finished fi i h d executing i

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

35

do/while Statement Semantics ` ` `

`

`

The statement is executed The control expression is evaluated If the control expression is true, true the previous steps are repeated Thi continues This ti until til th the control t l expression i becomes false At that th t point, i t the th statement t t t execution ti is i finished

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

36

Object Creation and Modification ` `

` `

` `

Objects j can be created with new The most basic object is one that uses the Object constructor, as in var myObject = new Object(); The new object has no properties - a blank object Dynamic properties - properties can be added to an object, any time var myAirplane = new Object(); myAirplane.make = "Cessna"; myAirplane.model = "Centurian"; Obj t can b Objects be nested, t d so a property t could ld b be it itself lf another th object, created with new Properties can be accessed by dot notation or in array notation as in notation, var property1 = myAirplane["model"]; delete myAirplane.model;

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

37

The for-in for in Loop `

`

`

Syntax for (identifier in object) statement or compound statement The loop lets the identifier take on each property in turn in the object Printing the h properties in my_car: for (var prop in my_car) document write("Name: " document.write("Name: ", prop prop, "; Value: " ", my_car[prop], "
");

`

Result: Name: make; Value: Ford Name: model; Value: Contour SVT

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

38

Arrays `

`

Also standard with the exception that you don't need to define what type(s) it may hold. Create a new array object. var myList = new Array(24, "bread", true); var myList2 = [24, "bread", true]; var myList3 = new Array(24);

`

Initialize some array cells. mylist[0]="hello"; mylist[0] hello ; mylist[1]=3.14; mylist[1000]=true;

`

The allowed indices are not pre-determined, but it's best to stick to standard array indexing, unlike the above example l which hi h skips ki some indices. i di SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

39

Array `

`

(continued)

Array variables are objects objects. JavaScript doesn't doesn t yet support classes and inheritance, but there are several built in classes with constructors (like Array() ) which are available. The length of an array is the highest subscript to which an element has been assigned, assigned plus 1 myList[122] = "bitsy";

`

// length is 123

Because the length property is writeable, you can set it to make the array any length you like, as in myList.length = 150; Æ SHOW insert_names.html

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

40

Array `

(continued)

Array methods

◦ join – e.g., var listStr = list.join(", "); ◦ reverse ◦ sort – e.g., names.sort();

x Coerces elements to strings and puts them in alphabetical order

◦ concat – e.g., newList = list.concat(47, 26); ◦ slice

listPart = list.slice(2, 5); listPart2 = list.slice(2); ◦ toString

x Coerce elements to strings, if necessary, and catenate them together, separated by commas (exactly like join(", "))

`

Dynamic list operations

`

A two-dimensional array in JavaScript is an array of arrays

◦ push, pop, unshift, and shift `

This need not even be rectangular shaped: different rows could have different length

Æ SHOW nested_arrays.html

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

41

JavaScript Objects `

Math Object

`

String Object

`

Date Object j

`

Boolean Object

`

Number Object

`

Window Object

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

42

The Math Object

Method

Description p

abs( x )

absolute value of x

ceil( x )

abs( 7.2 ) is 7.2 abs( 0.0 ) is 0.0 abs( -5.6 ) is 5.6 rounds x to the smallest integer not ceil( 9.2 ) is 10.0 ceil( il( -9.8 9 8 ) is i -9.0 9 0 less than x

cos( x )

trigonometric cosine of x (x in radians)

exp( x )

exponential method ex

floor( x )

Examples p

cos( 0.0 ) is 1.0

exp( 1.0 ) is 2.71828 exp( ( 2.0 2 0 ) is i 7.38906 7 38906 rounds x to the largest integer not floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0 greater than x

log( x )

natural logarithm of x (base e)

max( x, y )

larger value of x and y

min( x, y )

smaller value of x and y

pow( x, y )

x raised to power y (xy)

round( x )

rounds x to the closest integer

sin( x )

trigonometric sine of x (x in radians)

sqrt( x )

square root of x

tan( x )

trigonometric tangent of x (x in radians)

log( log( max( max( min( min(

2.718282 ) is 1.0 7 389056 ) is 2.0 7.389056 2 0 2.3, 12.7 ) is 12.7 -2.3, -12.7 ) is -2.3 2.3, 12.7 ) is 2.3 -2.3, -12.7 ) is -12.7

pow( 2.0, 7.0 ) is 128.0 pow( 9.0, .5 ) is 3.0 round( 9.75 ) is 10 round( 9.25 ) is 9 sin( 0.0 ) is 0.0

`

Provides a collection of properties and methods useful for Number values

sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0 tan( 0.0 ) is 0.0

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

43

Properties of The Math Object Constant

Description

Value

Math.E

Base of a natural logarithm (e).

Approximately 2.718

Math.LN2

Natural logarithm of 2

Approximately 0.693

Math.LN10

Natural logarithm of 10

Approximately 2.302

Math.LOG2E

Base 2 logarithm of e

Approximately 1.442

Math.LOG10E

Base 10 logarithm of e

Approximately 0.434

Math.PI

π—the ratio of a circle’s circumference i f t its to it diameter di t

Approximately 3 141592653589793 3.141592653589793

Math.SQRT1_2

Square root of 0.5

Approximately 0.707

Math.SQRT2

Square root of 2.0

Approximately 1.414

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

44

The String Object `

` ` ` `

Characters are the fundamental building blocks of JavaScript programs. Every program is composed of a sequence of characters grouped together meaningfully that is interpreted by the computer as a series of instructions used to accomplish a task. A string is a series of characters treated as a single unit. unit A string may include letters, digits and various special characters, such as +, -, *, /, and $. JavaScript supports Unicode, d which h h represents a large portion of the world’s languages. String literals or string constants (often called anonymous String objects) are written as a sequence of characters in double quotation marks or single quotation marks. SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

45

Some String Object Methods (1) Method

Description

charAt( index )

Returns a string containing the character at the specified index. If there is no character at the index, charAt returns an empty string. The first character is located at index 0.

charCodeAt( index )

Returns the Unicode value of the character at the specified index, or NaN (not a number) if there is no character at that index.

concat( string )

Concatenates its argument to the end of the string that invokes the method. The string invoking this method is not modified; i t d a new String instead St i is i returned. t d This Thi method th d is i the th same as adding two strings with the string-concatenation operator + (e.g., s1.concat(s2) is the same as s1 + s2).

fromCharCode( value1, value2, )

Converts a list of Unicode values into a string containing the corresponding p g characters.

indexOf( substring, index )

Searches for the first occurrence of substring starting from position index in the string that invokes the method. The method returns the starting index of substring in the source string or –1 if substring is not found. If the index argument is not provided, provided the method begins searching from index 0 in the source string.

lastIndexOf( substring, index )

Searches for the last occurrence of substring starting from position index and searching toward the beginning of the string that invokes the method. The method returns the starting index off substring b i in i the h source string i or –1 1 if substring b i is i not found. f d If the index argument is not provided, the method begins searching from the end of the source string.

replace( searchString, Searches for the substring searchString, and replaces the first occurrence with replaceString p g and returns the modified string, g, replaceString eplaceSt ing ) or the original string if no replacement was made.

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

46

Some String Object Methods (2) slice( start, end )

Returns a string containing the portion of the string from index start through index end. If the end index is not specified, the method returns a string from the start index to the end of the source string. A negative end index specifies an offset from the end of the string, starting from a position one past the end of the last character (so –1 indicates the last character p position in the string). g)

split( string )

Splits the source string into an array of strings (tokens), where its string argument specifies the delimiter (i.e., the characters that indicate the end of each token in the source string).

substr( start t t, length l th )

Returns a string containing length characters starting from index start i the in th source string. t i If length l th is i nott specified, ifi d a string t i containing t i i characters from start to the end of the source string is returned.

substring( start, end )

Returns a string containing the characters from index start up to but not including index end in the source string.

toLowerCase()

Returns a string in which all uppercase letters are converted to lowercase letters. Nonletter characters are not changed.

toUpperCase()

Returns a string in which all lowercase letters are converted to uppercase letters. Nonletter characters are not changed.

Methods that XHTML tags

g generate

anchor( name )

Wraps the source string in an anchor element () with name as the anchor name.

fixed()

Wraps the source string in a element (same as <pre>).

link( url )

Wraps the source string in an anchor element () with url as the hyperlink location.

strike()

Wraps the source string in a <strike> element.

sub()

Wraps the source string in a <sub> element.

sup()

Wraps the source string in a <sup> element. SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

47

String Catenation `

`

The operation + is the string catenation operation In many cases cases, other types are automatically converted to string

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

48

Concatenation (Duality of +) `

`

`

The concatenation operator is +. x="3"; y="4"; z=x+y; y // "34" a=y+x; // "43" But + is also used for addition of numbers. x=3; y=4; z=x+y; // 7 This duality is a problem since most data stored in HTML form elements is string data. We can parseFloat() (or parseInt()) data to force addition . "3" x="3"; y="4"; z= parseFloat(x)+parseFloat(y); // 7

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

49

Implicit Type Conversion `

`

`

`

`

`

`

JavaScript attempts to convert values in order to be able to perform operations "August" + 1977 causes the number to be converted to string g and a concatenation to be performed p

7 * "3" causes the string to be converted to a number and a multiplication to be performed

null is converted to 0 in a numeric context, undefined to NaN 0 is i iinterpreted t t d as a B Boolean l ffalse, l all ll other th numbers b are interpreted a true

The empty string is interpreted as a Boolean false false, all other strings (including “0”!) as Boolean true

undefined,, Nan and null are all interpreted p as Boolean false SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

50

Explicit Type Conversion `

Explicit conversion of string to number ◦ Number(aString) ◦ aString – 0 ◦ Number must begin the string and be followed by space or end of string

`

parseInt and parseFloat convert the beginning of a string but do not cause an error if a non-space follows the numeric part

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

51

The typeof Operator `

` `

Returns “number” number or “string” string or “boolean” boolean for primitive types Returns “object” object for an object or null Two syntactic forms ◦ typeof t f x ◦ typeof(x)

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

52

Date Object `

`

A Date object represents a time stamp, that is, a point in time A Date D t object is created with ith the ne new operator ◦ var now= new Date(); D t ()

◦ This creates a Date object for the time at which it was created

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

53

The Date Object: Methods (1) Method

Description

getDate() getUTCDate()

Returns a number from 1 to 31 representing the day of the month in local time or UTC.

g getDay() y() getUTCDay()

Returns a number from 0 (Sunday) to 6 (Saturday) representing the day of the week in local time or UTC.

getFullYear() getUTCFullYear() getHours() getUTCHours()

Returns the year as a four-digit number in local time or UTC.

getMilliseconds() getUTCMilliSeconds()

Returns a number from 0 to 999 representing the number of milliseconds in local time or UTC, respectively. The time is stored in hours, hours minutes, minutes seconds and milliseconds milliseconds.

getMinutes() getUTCMinutes()

Returns a number from 0 to 59 representing the minutes for the time in local time or UTC.

getMonth() getUTCMonth()

Returns a number from 0 (January) to 11 (December) representing the month in local time or UTC.

getSeconds() getUTCSeconds()

Returns a number from 0 to 59 representing the seconds for the time in local time or UTC.

getTime() g ()

Returns the number of milliseconds between January 1, 1970, and the time in the Date object.

getTimezoneOffset()

Returns the difference in minutes between the current time on the local computer and UTC (Coordinated Universal Time).

setDate( ( vall ) setUTCDate( val )

S the Sets h d day off the h month h (1 to 31) in i local l l time i or UTC. UTC

Returns a number from 0 to 23 representing hours since midnight in local time or UTC.

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

54

The Date Object: Methods (2) Sets the year in local time or UTC. UTC The second and third arguments setFullYear( y, m, d ) representing the month and the date are optional. If an optional argument setUTCFullYear( y, m, d ) is not specified, the current value in the Date object is used.

Sets the hour in local time or UTC. The second, third and fourth setHours( h, m, s, ms ) setUTCHours( h, m, s, ms ) arguments, representing the minutes, seconds and milliseconds, are

optional. If an optional argument is not specified, optional specified the current value in the Date object is used.

Sets the number of milliseconds in local time or UTC. setMilliSeconds( ms ) setUTCMilliseconds( ms ) Sets the minute in local time or UTC. The second and third arguments, g setMinutes( m, s, ms ) representing the seconds and milliseconds, are optional. If an optional setUTCMinutes( m, s, ms ) argument is not specified, the current value in the Date object is used.

setMonth( m, d ) setUTCMonth( m, d )

Sets the month in local time or UTC. The second argument, representing the date, is optional. If the optional argument is not specified, the current date value in the Date object is used. used

setSeconds( s, ms ) setUTCSeconds( s, ms )

Sets the second in local time or UTC. The second argument, representing the milliseconds, is optional. If this argument is not specified, the current millisecond value in the Date object is used.

setTime( ms )

Sets the time based on its argument—the g number of elapsed p milliseconds since January 1, 1970.

toLocaleString()

Returns a string representation of the date and time in a form specific to the computer’s locale. For example, September 13, 2007, at 3:42:22 PM is represented as 09/13/07 15:47:22 in the United States and 13/09/07 15:47:22 in Europe.

toUTCString()

Returns a string representation of the date and time in the form: 15 Sep 2007 15:47:22 UTC

toString()

Returns a string representation of the date and time in a form specific to the locale of the computer (Mon Sep 17 15:47:22 EDT 2007 in the United States). )

valueOf()

The time in number of milliseconds since midnight, January 1, 1970. (Same as getTime.) SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

55

Boolean and Number Objects `

`

`

JavaScript provides the Boolean and Number objects as object wrappers for boolean true/false values and numbers, respectively. When a boolean value is required in a JavaScript program, JavaScript automatically creates a Boolean object to store the value. JavaScript programmers can create Boolean objects explicitly with the statement var b = new Boolean( booleanValue ); The argument booleanValue specifies the value of the Boolean object (true or false). If booleanValue is false, 0, null, Number.NaN or the empty string (""), or if no argument is supplied, supplied the new Boolean object contains false. false Otherwise, the new Boolean object contains true.

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

56

The Boolean Object: Methods

Method

Description

toString() Returns the string "true" if the value of the Boolean object is true; otherwise, th i returns t the th string t i "false" false . valueOf() Returns the value true if the Boolean object is true; otherwise, returns false.

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

57

The Number Object: Methods Method or property

Description

toString( radix )

Returns the string representation of the number. The optional radix argument (a number from 2 to 36) specifies the number’s base. For example, radix 2 results in the binary representation of the number, 8 results in the octal representation, 10 results in the decimal representation and 16 results in the hexadecimal representation. See Appendix E, Number Systems, for a review of the binary, octal, decimal and hexadecimal number systems.

valueOf()

Returns the numeric value.

Number.MAX_VALUE

This property represents the largest value that can be stored in a JavaScript program—approximately program approximately 1.79E+308. 1 79E+308

Number.MIN_VALUE

This property represents the smallest value that can be stored in a JavaScript program—approximately 5.00E–324.

Number.NaN

This property represents not a number—a value returned from an arithmetic expression that does not result in a number b ((e.g., the h expression i parseInt( ( "hello" "h ll " ) cannot convert the string "hello" into a number, so parseInt would return Number.NaN. To determine whether a value is NaN, test the result with function isNaN, which returns true if the value is NaN; otherwise it returns false. otherwise, false

Number.NEGATIVE_INFINITY This property represents a value less than Number.MAX_VALUE. Number.POSITIVE_INFINITY This property represents a value greater than Number.MAX_VALUE. SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

58

The Number Object `

Properties ◦ ◦ ◦ ◦ ◦ ◦

`

MAX_VALUE MIN VALUE MIN_VALUE NaN POSITIVE_INFINITY NEGATIVE_INFINITY PI

Operations resulting in errors return NaN ◦ Use isNaN(a) to test if a is NaN

`

toString method converts a number to string

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

59

Window and Document Objects `

`

`

The Window object represents the window in which the document containing the script is being displayed The Document object represents the document being displayed using DOM Wi d Window h has ttwo properties ti ◦ window refers to the Window object itself ◦ document refers to the Document object

`

The Window object is the default object for JavaScript, so properties and methods of the Window object may be used without qualifying with the class name SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

60

The Document Object: Methods & Properties Method or property

Description

getElementById( id ) Returns the DOM node representing the XHTML element whose id attribute matches id. write( string )

Writes the string to the XHTML document as XHTML code.

writeln( string )

Writes the string to the XHTML document as XHTML code and adds a newline character at the end.

cookie

A string containing the values of all the cookies stored on the user’s computer for the current document. See Section 11.9, Using Cookies.

lastModified

The date and time that this document was last modified.

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

61

Screen Output and Keyboard Input `

` `

`

`

`

`

The JavaScript model for the HTML document is the Document object The model for the browser display window is the Window object The h Window object b h has two properties, document and d window, which refer to the Document and Window objects, respectively The e Document ocu e t object has as a method, et od, write, te, which c dy dynamically a ca y creates content The parameter is a string, often catenated from parts, some of which are variables e.g., document.write("Answer: " + result + "
"); The parameter is sent to the browser, so it can be anything that can appear in an HTML document (
, but not \n) The Window object has three methods for creating dialog boxes alert, alert confirm, confirm and prompt boxes, SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

62

The Window Object: Methods & Properties Method or property

Description

open( url, name, options )

Creates a new window with the URL of the window set to url, the name set to name to refer to it in the script, and the visible features set by the string passed in as option.

prompt( prompt, default )

Displays a dialog box asking the user for input. The text of the dialog is prompt, and the default value is set to default.

close()

Closes the current window and deletes its object from memory.

focus()

This method gives focus to the window (i.e., puts the window in the foreground, on top of any other open browser windows) windows).

blur()

This method takes focus away from the window (i.e., puts the window in the background).

window.document

This property contains the document object representing ti the th document d t currently tl inside i id the th window. i d

window.closed

This property contains a boolean value that is set to true if the window is closed, and false if it is not.

window.opener

This p property p y contains the window object j of the window that opened the current window, if such a window exists. SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

63

The alert Method `

`

The alert method opens a dialog box with a message The output of the alert is not XHTML, XHTML so use new lines rather than
alert("The sum is:" + sum + "\n");

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

64

The confirm Method `

The confirm methods displays a message provided as a parameter ◦ The confirm dialog has two buttons: OK and Cancel

`

`

If the user presses OK, true is returned by the method If the h user presses Cancel, C l false f l is i returned d

var question = confirm("Do y you want to continue this download?");

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

65

The prompt Method `

This method displays its string argument in a dialog box ◦ A second argument provides a default content for the user entry area

` `

The dialog box has an area for the user to enter text The method returns a String g with the text entered by y the user name = prompt("What is your name?", "");

Æ SHOW roots.html SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

66

Function Fundamentals `

Function definition syntax

◦ A function definition consist of a header followed by a compound statement ◦ A function header: x function function-name(optional-formal-parameters)

`

return statements

◦ A return statement causes a function to cease execution and control to pass to the caller ◦ A return statement may include a value which is sent back to the caller x This value may be used in an expression by the caller

◦ A return statement without a value implicitly returns undefined

`

Function call syntax

◦ F Function i name ffollowed ll db by parentheses h and d any actuall parameters ◦ Function call may be used as an expression or part of an expression

`

Functions must defined before use in the page header

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

67

Functions `

`

The syntax for functions is standard, with the exception that you don'tt declare types for parameters or for returned values don values.

Here is an example of a void (no return value) style function. function customrule(width,char) { for (var x=1 ; x<=width ; x++) { document.write(char); } document.write("
"); }

`

Here is a sample call to the function function. customrule(25,"#");

`

Here is the result in the Web page. ######################### SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

68

Functions ` `

` `

`

`

(continued)

Return value is the parameter of return If there is no return, or if the end of the function is reached, undefined is returned If return has no parameter, undefined is returned Functions are objects, so variables that reference them can be b ttreated t d as other th object bj t references f If fun is the name of a function, ref fun = fun; ref_fun ... ref_fun(); () /* A call to fun */ We place all function definitions in the head of the HTML document SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

69

Functions are Objects ` `

Functions are objects in JavaScript Functions may, therefore, be assigned to variables and to object j p properties p

◦ Object properties that have function values are methods of the object

`

E Example l

function fun() { document.write("This document.write( This surely is fun!
");
); } ref_fun = fun; // Now, ref_fun refers to the fun object fun(); // A call to fun ref_fun(); // Also a call to fun

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

70

Local Variables `

`

`

`

“The The scope of a variable is the range of statements over which it is visible” A variable not declared using g var has g global scope, p , visible throughout the page, even if used inside a function definition A variable i bl d declared l d with i h var outside id a ffunction i definition has global scope A variable declared with var inside a function definition has local scope, visible only inside the function definition ◦ If a global variable has the same name, it is hidden inside the function definition

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

71

Parameters

`

Parameters named in a function header are called formal parameters Parameters used in a function call are called

`

Parameters are passed by value

`

actual parameters

◦ For an object parameter, the reference is passed, so the function body can actually change the object ◦ However, an assignment to the formal parameter will not change the actual parameter

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

72

Parameter Passing Example function fun1(my_list) { var list2 = new Array(1, 3, 5); my_list[3] li t[3] = 14; 14 ... my_list = list2; ... } ... var list = new Array(2 Array(2, 4, 4 6, 6 8) fun1(list);

` `

`

The first Th fi t assignment i t changes h list li t in i the th caller ll The second assignment has no effect on the list object in the caller Pass by reference can be simulated by passing an array y containing g the value SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

73

Parameter Checking `

JavaScript checks neither the type nor number of parameters in a function call ◦ Formal parameters have no type specified ◦ Extra actual parameters are ignored (however, see below) ◦ If there are fewer actual parameters than formal parameters, the extra formal parameters remain undefined

` `

This is typical of scripting languages A property array named arguments holds all of the actual t l parameters, t whether h th or nott there th are more off them than there are formal parameters ◦ Example params.js illustrates this

Æ SHOW parameters.html SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

74

Functions `

(continued)

Scope example:

function scopedemo(x) { var y=10; x++; y=x+y; z++; } var x=2; var y=3; var z=4; scopedemo(z);

`

Result: After the function call, the state of the global variables are x<-->2,

`

`

y<-->3,

z<-->5

Note that global variables "live" so long as the page is loaded into the browser. Refreshing the page, rere initializes global variables. Local variables "live" only during the function call. SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

75

The sort Method, Method Revisited `

A parameter can be passed to the sort method to specify how to sort elements in an array

◦ The parameter is a function that takes two parameters ◦ The function returns a negative value to indicate the first parameter should come before the second ◦ The function returns a positive value to indicate the first parameter should come after the second ◦ The Th function f i returns 0 to indicate i di the h fi first parameter and the second parameter are equivalent as far as the ordering is concerned

`

Example median.js illustrates the sort method

Æ SHOW medians.html medians html SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

76

Constructors `

`

`

Constructors are functions that create an initialize properties for new objects A constructor uses the keyword this in the body to reference the object being initialized Object methods are properties that refer to functions ◦ A function to be used as a method may use the keyword this to refer to the object for which it is acting g

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

77

Constructor Example `

Used to initialize objects objects, but actually create the properties function plane(newMake, plane(newMake newModel newModel, newYear){ this.make = newMake; this.model = newModel; this.year = newYear; } myPlane = new plane( plane("Cessna", Cessna , "Centurnian", "1970");

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

78

Constructor Example (continued) `

Can also have method properties function displayPlane() { document.write("Make: ", this.make, "") "
"); document.write("Model: ", this.model, "
"); document write("Year: " document.write("Year: ", this this.year, year "
"); }

`

N Now add dd th the ffollowing ll i tto th the constructor: t t this.display = displayPlane;

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

79

Pattern Matching `

` `

`

JavaScript provides two ways to do pattern matching: 1. Using RegExp objects 2. Using methods on String objects Si Simple l patterns Two categories of characters in patterns: ◦ a. a normal characters (match themselves) ◦ b. metacharacters (can have special meanings in patterns--do not match themselves) \ | ( ) [ ] { } ^ $ * + ? . A metacharacter is treated as a normal character if it is b k l h d backslashed ◦ period is a special metacharacter - it matches any character except newline SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

80

Using Regular Expressions `

`

Regular expressions are used to specify patterns in strings JavaScript provides two methods to use regular expressions in pattern matching ◦ String methods ◦ RegExp objects (not covered in the text)

`

`

A literal regular expression pattern is indicated by enclosing the pattern in slashes The search method returns the position of a match, if found, or -1 if no match was found SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

81

Pattern Matching `

search(pattern)

`

Character classes

`

(continued)

◦ Ret Returns rns the position in the object string of the pattern (position is relative to zero); returns -1 if it fails var str = "Gluckenheimer"; var position = str.search(/n/); /* position is now 6 */

◦ Put a sequence of characters in brackets, and it defines a set of characters, any one of which matches [abcd] ◦ Dashes can be used to specify spans of characters in a class [a-z] A caret at the h left l f end d off a class l definition d fi i i means the h opposite i [^0-9]

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

82

Example Using search var str = "Rabbits are furry"; var position = str.search(/bits/); if (position > 0) document write("'bits' document.write( bits appears in position" position , position, "
"); else document.write( "'bits' does not appear in str
"); `

`

This uses a pattern Thi tt th thatt matches t h th the string t i ‘bits’ Th output off this The hi code d iis as ffollows: ll 'bits' appears in position 3

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

83

Characters and Character Character-Classes Classes `

Metacharacters have special meaning in regular expressions

◦ \|()[]{}^$*+? . ◦ These characters may be used literally by escaping them with \

` `

Other characters represent themselves A period matches any single character

◦ /f.r/ matches for and far and fir but not fr

`

A character class matches one of a specified set of characters ◦ [character set] ◦ ◦ ◦ ◦

List characters individually: [abcdef] Give a range of characters: [a-z] Beware of [A-z] t e beginning beg g negates egates the t ec class ass ^ at the

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

84

Predefined character classes

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

85

JavaScript Pattern Special Characters Character .

Matches Any character except NEWLINE

*

Preceding item zero or more times

+

Preceding item one or more times

?

Preceding item zero or one time

{n}

Preceding item n times

{m n} {m,n}

Preceding item m to n times (n can be discarded)

(x)

Item x, captures matching string

|y x|y

Item x or item y

[abc]

Any one of listed characters

[^abc]

Any character not listed

\d*

zero or more digits

\d+

one or more digits

\d?

zero or one digit SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

86

Repeated Matches `

`

A pattern can be repeated a fixed number of times by following it with a pair of curly braces enclosing a count A pattern can be repeated by following it with one of the following special characters ◦ * indicates i di t zero or more repetitions titi off th the previous i pattern previous p pattern ◦ + indicates one or more of the p ◦ ? indicates zero or one of the previous pattern

`

Examples

◦ /\(\d{3}\)\d{3}-\d{4}/ might represent a telephone number /[$ a-zA-Z][$ a-zA-Z0-9]*/ ◦ /[$_a-zA-Z][$_a-zA-Z0-9] / matches identifiers SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

87

Anchors `

Anchors in regular expressions match positions rather than characters ◦ Anchors are 0 width and may not take multiplicity modifiers

`

Anchoring to the end of a string ◦ ^ at the beginning of a pattern matches the beginning of a string ◦ $ at the end of a pattern matches the end of a string x The $ in /a$b/ matches a $ character

`

Anchoring at a word boundary

◦ \b matches the position between a word character and a non-word character h or the h beginning b i i or the h end d off a string i ◦ /\bthe\b/ will match ‘the’ but not ‘theatre’ and will also match ‘the’ in the string ‘one of the best’ e.g., /^Lee/ matches "Lee Ann" but not "Mary Lee Ann" /Lee Ann$/ matches "Mary Lee Ann", but not "Mary Lee Ann is nice" SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

88

Pattern Modifiers `

The i modifier tells the matcher to ignore the case of letters /oak/i matches "OAK" and "Oak" and …

`

The x modifier tells the matcher to ignore whitespace hi in i the h pattern (allows ( ll comments in patterns)

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

89

Other Pattern Matching Methods `

The replace method takes a pattern parameter and a string parameter

◦ The method replaces a match of the pattern in the target string with the second parameter ◦ A g modifier on the pattern causes multiple replacements

`

Parentheses can be used in patterns to mark sub-patterns ◦ The pattern matching machinery will remember the parts of a matched string that correspond to sub-patterns

`

The match method takes one pattern parameter ◦ Without a g modifier, f the return is an array off the match and parameterized sub-matches

◦ With a g modifier, the return is an array of all matches

`

The split method splits the object string using the pattern to specify the split points

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

90

Other Pattern Matching g Methods (continued) `

Other Pattern Matching Methods of String replace(pattern, string)

`

Finds a substring g that matches the pattern p and replaces it with the string (g modifier can be used) var str = "Some rabbits are rabid"; str.replace(/rab/g, "tim"); x str is now "Some timbits are timid"

x $1 and $2 are both set to "rab" rab

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

91

Other Pattern Matching g Methods (continued) `

match(pattern) ◦ The most general pattern-matching method ◦ Returns an array of results of the pattern-matching operation ◦ With the g modifier, it returns an array of the substrings that matched ◦ Without the g modifier, first element of the returned array has the matched substring, the other elements have the values of $1, … var str = “Having 4 apples is better than having 3 oranges"; var matches = str.match(/\d/g); x matches is set to [ [4, , 3] ]

`

split(parameter)

var str = “grapes:apples:oranges”; var fruit = str.split(“:”); f it is set to [ l ] x fruit [grapes, apples, oranges]

Æ SHOW forms_check.html

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

92

Pattern Examples Pattern

Matching Strings

/l.ve/

love, live, lxve, l+ve, …

/^http/ / http/

http at the beginning of a string

/edu$/

edu at the end of the string

/L+/

L,, LL,, LLL,, LLLL,, …

/BK*/

B, BK, BKK, …

/D+HD/

DHD, DDHD, DDDHD, …

/.G*/

Any string ending in G

/G?G/

G or GG

/^$/

Empty string

/[a-z]9/

A9, b9,…, or z9

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

93

Using Cookies `

`

`

`

`

A cookie is a piece of data that is stored on the user’s user s computer to maintain information about the client during and between browser sessions. M i C Magic Cookies ki -- Introduced I t d db by N Netscape t with ith th the release l off NN2 in 1996. Soon became an official "extension" of the HTTP protocol and supported by all browsers. A harmless way to have a Web browser store some data on the client between transactions transactions. Why do you want to study cookies in some detail? Go to the preferences of a Web browser and turn on the feature which gives i an alert l t upon each h cookie ki which hi h is i sett on th the browser b . Surf around for a while. Question answered.

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

94

What are Cookies? `

` `

The data portion of each cookie consists of only one name=value pair. Each cookie is specific to a Web domain domain. So a basic cookie has the form www.uweb.edu b d

`

name=value l

This is not necessarily how a Web browser formats a cookie as text when it saves it. it That is entirely up to a particular browser. We only need to understand the parts which comprise a cookie. SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

95

How do cookies originate? `

`

They can be set using JavaScript. JavaScript Cookies are are, in fact, the only "writing" that JavaScript can do to the client client's s file system. system The utility of cookies comes into play when CGI programs set cookies cookies, and then retrieve them in a subsequent transaction. ◦ Thus Thus, one use for cookies is for storing state data -- on the client!! ◦ There are other uses like: storing session IDs and user preferences for a given Web site.

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

96

The General Idea Behind Cookies 1. A CGI program sends a cookie(s) to a browser. 2. The browser stores the cookie ◦ In a cookie file for persistent cookies ◦ In a RAM cache for session cookies

3 In any subsequent transaction 3. with the domain which set the cookie(s), the browser automatically sends back the cookie(s). SCCS426 Internet Technology and Its Applications by Asst.Prof.Dr. Thanwadee Sunetnanta, SCCS426 Internet Technology and Its Applications, Mahidol ICT Programme, University, Semester 2/2008 2/2006

97

Cookies Types `

Session cookies are meant to live for the duration of a browsing session, session much like a state file. file

◦ Depending upon the particular browser, a cache of session cookies might g be maintained for a given g browser window and purged when the window is closed. ◦ Or the session cookies might be common to all windows open in i a given i b browser and d purged d when h th the application li ti iis quit.

`

When a cookie is set with an expires field, it becomes a persistent cookie in the cookie file. www.uweb.edu name1=value1 03 24 33 GMT 2005 03:24:33

expires=Thu, 01-Jan-

◦ A browser automatically polices the persistent cookie file, deleting expired ones. SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

98

Fields Used to Customize Cookies ` `

The only required field to set in a cookie is its data -- the name=value pair. There are 4 other optional fields

name=value l (mandatory)

The name identifies the cookie. Set a cookie with a name already in use, the new cookie replaces the old one.

expires=date

S Special i l format f f expiration for i i dates: d

(optional)

Fri, 03-Nov-2001 15:09:33 GMT

domain=domainname

The default is to send back onlyy to domain which set the cookie (e.g. www.uweb.edu)

(optional)

Can generalize: domain=uweb.edu Can restrict: path=directorypath (optional)

domain domain= xx.y.uweb.edu y uweb edu

Can also restrict where cookie is returned based on URL path path= /~jones

secure

Return only if transaction is using https

(optional)

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

99

1



2


3

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4 5



6



7



8



9

Using Cookies

10

<script type = "text/javascript">

11



69



70



71



72 73

Forces the p page g to refresh,, and will prompt the user to enter a name, as there will be no cookie

Click Refresh (or Reload) to run the script again



74

102

Using cookies to store user identification data (4)

103

Third-Party Third Party Cookies `

` `

Use a Web browser that has the feature turned on which gives an alert when a cookie is set. Go to a few major j commercial sites and observe that some of the incoming cookies are from a different domain than the site you have pulled up. Question: How is that possible? Answer: There are images in the Web page whose source files fil reside id on a third thi d party t server. We W will ill call such images third party images. During the transaction to acquire the third party image image, the third party server sets a cookie on the browser -- a third party cookie. SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

10 4

Third-Party Third Party Cookies `

`

`

`

`

(continued)

Your browser and the server giving you the Web page are the first two parties -- the primary parties in the transaction. Your browser reads the src of the HTML image element as it parses the th fil file and d makes k a secondary d requestt for f the th graphic hi from the third party server. Normally, this secondary request is made to the server which is serving up the HTML page. Typically, a third party image is put in a page solely to cause a secondary transaction with a third party server server. The purpose of such secondary transactions is to set (and read) cookies. Ob i Obviously, l thi this iis nott standard t d d HTTP server software, ft b butt software modified to deal in cookies upon image requests.

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

10 5

Setting a Third-Party Third Party Cookie

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

10 6

Errors in Scripts ` `

JavaScript errors are detected by the browser Different browsers report this differently ◦ Firefox uses a special console

`

Support for debugging is provided

◦ In IE 7, the debugger is part of the browser ◦ For Firefox 2, plug-ins are available x These include Venkman and Firebug

SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

10 7

Debugging JavaScript `

`

IE6 ◦ Select Internet Options from the Tools menu ◦ Choose the Advanced tab ◦ Uncheck the Disable script debugging box ◦ Check the Display a notification about every script error box ◦ Now, N a script i t error causes a small ll window i d tto b be opened d with ith an explanation of the error

NS7 ◦ Select Tools, Web Development, and JavaScript Console ◦ A small window appears to display script errors ◦ Remember to Clear the console after using an error message – avoids confusion SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

10 8

Using JSON to Represent Objects ` ` `

JSON (JavaScript Object Notation) is a simple way to represent JavaScript objects as strings. JSON was introduced in 1999 as an alternative to XML for f data d exchange. h Each JSON object is represented as a list of property names and values contained in curly braces, in the following format: { propertyName1 : value1, propertyName2 : value2 }

`

Arrays are represented in JSON with square brackets in the following format: [ value1, l 1 value2, l 2 value3 l 3 ]

`

Values in JSON can be strings, numbers, JSON objects, true, false or null. http://www.json.org/ SCCS426 Internet Technology and Its Applications, ICT Programme, Semester 2/2008

10 9

Related Documents

Lect03
June 2020 3