1 javascript web and database management system. 2 javascript javascript is a scripting language...

48
1 Javascript Web and Database Management System

Upload: lucinda-daniel

Post on 03-Jan-2016

221 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

1

Javascript

Web and Database

Management System

Page 2: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

2

Javascript

• Javascript is a scripting language– There is no need to compile the code before executing

• JS is a client-side program, which can be run on any JS-supported browser, ie. Firefox, IE, Safari, Opera, etc.

• JS can be embedded in the HTML file or imported from a separate JS file

Page 3: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

3

Imported JS

//Javascript inline commentwindow.alert("Hello World!");

hello.js

<html><head><title>JSHelloWorld.html</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script type="text/javascript" src="hello.js"></script>

</head><body></body></html>

JSHelloWorld.html

Page 4: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

4

Embedded JS

<html><head><title>JSHelloWorld.html</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script type="text/javascript">window.alert(“Hello World!”);

</script></head><body></body></html>

JSHelloWorld.html

Page 5: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

5

JS Input

<html><head><title>JSHelloWorld.html</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script type="text/javascript"> var inString = window.prompt(“Please enter your number”, “100”); </script></head><body></body></html>

JSInput.html

Page 6: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

6

JS Print

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>document.write()</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head><body> <H1><center>Javascript</center></H1>

<script language="JavaScript">document.write("<p>Hello World!!!</p>");document.write("<span id=\"spid\">Good Planet!!!</span>");

</script></body></html>

Page 7: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

7

var rndNumber; //Number the computer randomsvar guess = -1; //User's latest guessvar count = 1; // Count number of guess

rndNumber = Math.ceil(Math.random()*1000);

while(guess!=rndNumber && count <= 10){ guess = window.prompt(count + ": Pick number between 1 and 1000.","");

if(guess<rndNumber) window.alert("Your guess of " + guess + " was too low");

else if(guess>rndNumber)window.alert("Your guess of " + guess + " was too high");

else {window.alert("Your got it! [" + rndNumber +"]");break;

} count = count + 1; //count += 1; or count++;}if(count>10) window.alert("You lost!!!");

Page 8: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

8

Variables and Data Types

• Variables in JS do not have data types

• However, every variable has a value, and every variable belongs to one of the six JS data types:

1. Number

2. String

3. Boolean

4. Null

5. Object

6. Undefined (variable that has been declared but has not been assigned a value.

Page 9: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

9

Values Returned by typeof

Operand Value String typeof Returns

null object

Boolean boolean

Number number

String string

Native Object representing function function

Native Object not representing function object

Declared variable with no value undefined

Undeclared variable undefined

Nonexistent property of an Object undefined

var i;var j;j = "Not a number";alert("i is " + (typeof i) + "\n" + "j is " + (typeof j));

i is undefinedj is string

Page 10: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

10

JS Statements

• Expression statement– A statement that consists entirely of an expression

• Block statement– A set of statements enclosed in braces { and }

• Keyword statement– Statements that begin with keywords such as var , if, etc.

i = 5;j++;m==true;

{ x = 5; y = 10 area = x * y;}

var i;if score < 50 window.alert(“You failed.”);

Page 11: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

11

Some JS Keyword Statements

Statement Name Syntax

If-then if (expr) stmt

If-then-else if (expr) stmt else stmt

Do do stmt while (expr)

While while (expr) stmt

For for (part1; part2; part3) stmt

Continue continue

Break break

Return-void return

Return-value return expr

Switch switch (expr) { cases }

Try try try-block catch-part

Throw throw expr

Page 12: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

12

Operators

• Binary Operators– Has two operands, such as:

• Unary Operators– Has a single operand.– A unary operator may be either prefix or postfix – – i.e.

• Ternary Operators– Has three operands– The conditional operator is a good example– i.e. window.alert(“You “ + (score<50)?”fail”:”pass”);

a*b; x+y;

++i; i--; ~x;

Page 13: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

13

Literals

• Literals are strings of characters that represent values in the language:

– null = Null data type

– true and false = Boolean values

– Numbers can be written as integer (whole number) or decimals• Scientific notation: -12.4e12 means -12.4 x 1012

• Hexadecimal notation: 0xfa00• Magnitude of numbers: 10308 and 10-323

– String: a quoted string of characters (“xxx”)

– Unicode: \u005c

Page 14: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

14

Array

• Array can be created as:– Use the Array constructor with no argument

– Initialize values with Array constructor

– Create two-dimensional array

var ary1 = new Array();

var ary2 = new Array( 4, true, “OK”);

var ary3 = [ 4, true, “OK” ];

var ary2d = [ [ “X”, “0”, “0” ] , [ “0”, “X”, “0” ] , [ “0”, “X”, “X” ] ];

Page 15: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

15

Functions

• A function in JS is composed of:– The keyword function– Identifier representing function name– List of identifiers representing formal parameter list– The statements representing function body

var message = "Left";

function change(message) {message = "Right";window.alert(message);return;

}

change(message);window.alert(message);

Page 16: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

16

<html><head><title>JS Dom</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head>

<body>

<h1 id=“header”>The Javascript DOM</h1>

<p>DOM is "Document Object Model”.</p>

<ul id=“list”><li>Document = the web page</li><li>Object = virtual objects</li><li>Model = map</li>

</ul>

</body></html>

Javascript DOM

html

head

meta titlebody

h1 p ul

li li li

Page 17: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

17

Javascript Language Hierarchy

Navigator

Mimetype

Anchor

Location

Window

Frame History Document

Area Form Image

Language

Array Boolean Date NumberMath String

Link

Button Checkbox Hidden Option Password Radio Reset Select Submit Text Text Area

Page 18: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

18

Example of HTML Code

<html><head> <title>JS Dom</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1“ /></head>

<body> <h1 id=“header”>The Javascript DOM</h1>

<p>DOM is “Document Object Model”.</p>

<ul id=“list”><li><a href=“www.sun.com”>Go to Sun</a></li><li><a href=“www.cnn.com”>Go to CNN</a></li><li><a href=“www.nbc.com”>Go to NBC</a></li>

</ul></body></html>

Page 19: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

19

Retrieving Elements

• document.getElementById(“ID name”)– Returns the element with reffered ID

• document.getElementsByTagName(“Tag name”)– Returns an array of all elements with the reffered tag.

Page 20: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

20

<h1 id=“header”>The Javascript DOM</h1>

<p>DOM is "Document Object Model”.</p>

<ul id=“list”><li><a href=“www.sun.com”>Go to Sun</a></li><li><a href=“www.cnn.com”>Go to CNN</a></li><li><a href=“www.nbc.com”>Go to NBC</a></li>

</ul>

Retrieving Element by ID

x = document.getElementById(‘list’);

Page 21: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

21

<h1 id=“header”>The Javascript DOM</h1>

<p>DOM is "Document Object Model”.</p>

<ul id=“list”><li><a href=“www.sun.com”>Go to Sun</a></li><li><a href=“www.cnn.com”>Go to CNN</a></li><li><a href=“www.nbc.com”>Go to NBC</a></li>

</ul>

Retrieving Element by Tag Name

x = document.getElementByTagName(‘li’);

Page 22: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

22

<h1 id=“header”>The Javascript DOM</h1>

<p>DOM is "Document Object Model”.</p>

<ul id=“list”><li><a href=“www.sun.com”>Go to Sun</a></li><li><a href=“www.cnn.com”>Go to CNN</a></li><li><a href=“www.nbc.com”>Go to NBC</a></li>

</ul>

Retrieving Element by Tag Name

x = document.getElementByTagName(‘li’);node = x[2];

Page 23: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

23

<h1 id=“header”>The Javascript DOM</h1>

<p>DOM is "Document Object Model”.</p>

<ul id=“list”><li><a href=“www.sun.com”>Go to Sun</a></li><li><a href=“www.cnn.com”>Go to CNN</a></li><li><a href=“www.nbc.com”>Go to NBC</a></li>

</ul>

Retrieving Element by ID

x = document.getElementById(‘list’);node = x.childNodes;

Page 24: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

24

<h1 id=“header”>The Javascript DOM</h1>

<ul id=“list”><li><a href=“www.sun.com”>Go to Sun</a></li><li><a href=“www.cnn.com”>Go to CNN</a></li><li><a href=“www.nbc.com”>Go to NBC</a></li>

</ul>

Accessing the Children

x_first = document.getElementById(‘list’).firstchild;

x_last = document.getElementById(‘list’).lastchild;

Page 25: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

25

Chaining the Methods

• We can reach the node faster by chaining the methods

<h1 id=“header”>The Javascript DOM</h1>

<ul id=“list”><li><a href=“www.sun.com”>Go to Sun</a></li><li><a href=“www.cnn.com”>Go to CNN</a></li><li><a href=“www.nbc.com”>Go to NBC</a></li>

</ul>

document.getElementById(‘list’).getElementsByTagname(‘li’)[1].firstchild;

Page 26: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

26

Creating Form

<form name="frmLogin" method="post" onsubmit="return check()"> <table width="400"> <tr><td>Username:</td> <td><input type="text" name="txtUser" id="txtUser" />

<span id="usrSpan" style="color: red">*required</span></td> </tr> <tr><td>Password:</td> <td><input type="password" name="passwd" id="passwd" />

<span id="passwdSpan" style="color: red">*required</span></td> </tr> <tr align="center"> <td colspan="2"><input type="reset" value="Cancel" />&nbsp;

<input type="submit" /></td> </tr> </table></form>

Page 27: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

27

<script language="JavaScript">var regExCheck = new RegExp("^\\d{3}$");function check(){

var usr = document.frmLogin.txtUser;var pas = document.frmLogin.passwd.value;if(usr.value == "") {

alert("You must enter username.");usr.focus();document.getElementById('usrSpan').innerHTML = "xxxx";return false; }

if(pas == "") {alert("You must enter password.");document.frmLogin.passwd.focus();//alert(document.getElementById('passwdSpan').firstChild.nodeValue);document.getElementById('passwdSpan').firstChild.nodeValue = “xxxx”;return false; }

if(regExCheck.test(pas)) alert("str: OK");else {

alert("str: Not OK");document.frmLogin.passwd.value = "";document.frmLogin.passwd.focus();return false;}

return true;}</script>

Page 28: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

28

Regular Expression

Page 29: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

29

Regular Expression

• Regular expression is a way of representing a set of strings• It is often used to test that a string entered in an HTML

form – has a certain format or;– Belongs to the set of strings that have correct format

• An example of the set of strings that consist of three digits– \d\d\d

var acTest = new RegExp("^\\d\\d\\d$");

if(!acTest.test(areaCode) {window.alert(areaCode + " is not valid.");

}

var acTest = /^\d\d\d$/;

Page 30: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

30

JS Multicharacter Escape Codes

Escape Code Characters Presented

\d Digit: 0 through 9

\D Any characters NOT in \d

\s Space: any JS white space or line terminator

(space, tab, line feed, etc.)

\S Any characters NOT in \s

\w “Word” character: any letter (a through z and A through Z),

digit (0 through 9), or underscore(_)

\W Any characters NOT in \w

Page 31: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

31

More Complex Regular Expression

• The simplest form of RegExp is a character that is not on of these RegExp special characters:

• Simple regular expression can be composed into more complex RegEX using one of three types of operators

1. Concatenation2. Union3. Kleene star

^ $ \ . * + ? ( ) [ ] { } |

Page 32: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

32

Concatenation

• Two or more RegExps can be concatenated as:

– This represents the set of strings beginning with a single digit followed by a period, a space, and terminating a “word” character (letter, digit, or underscore).

^\d\. \w$

2. 12. x0. _

3.A7. J

These are not OK because: - The first doesn’t have space. - The second has two spaces.These are OK.

Page 33: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

33

Concatenation (cont)

• When we want to concatenate itself many times, we can use the quantifier notation:

– The set of all strings of exactly three digits

– Strings that begin with a – followed by three digits

– This is any string from three through six digits, or using Union as: (see next slide)

\d{3}

-\d{3}

\d{3,6}

\d\d\d|\d\d\d\d|\d\d\d\d\d|\d\d\d\d\d\d

Page 34: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

34

Union

• Union operator is represented by the pipe symbol, “|”

– The set consisting of all digit and white space characters.

– String consisting of + and two-character strings beginning with – followed by a digit, and the white space characters.

– Note: This is because concatenation has higher priority than union. So, use parentheses.

\d|\s

\+|-\d|\s

(\+|-)\d|\s

Page 35: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

35

Class

• We can use “character class” to represent a set of all lowercase/uppercase characters or all digit

– This represents the set of lowercase letters

– This is equivalent to the escape code: \w

[a-z]

[a-zA-Z0-9]|_

Page 36: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

36

Kleen Star

• Kleen star allows us to represent infinitely large sets

– This represents the set of strings of any number of digits, including empty string.

– An example of valid password that must contain at least one digit and at least one letter and may only contain digits, letters, and underscores

\d*

\w*(\d\w*[a-zA-Z]|[a-zA-Z]\w*\d)\w*

Page 37: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

37

Regular Expression

Derived from: http://www.zytrax.com/tech/web/regex.htm

Page 38: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

38

Definitions

Terms Description

Literal Any character used in search or matching expression, i.e. to find ind in windows the ind is a literal string

Metacharacter One or more special characters that have a unique meaning and are NOT used as literals in the search expression, i.e. character ^ (circumflex or caret) is a metacharacter

Escape Sequence A way of indicating that we want to use one of our metacharacters as a literal, using \ (backslash) in front of metacharacter, i.e. find ^ind in w^indows then we use \^ind, use C:\\file.txt to find c:\file.txt.

Target String String in which we want to find our match or search pattern.

Search Expression Expression that we use to search our target string, that is, the pattern we use to find what we want

Page 39: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

39

Our Example Target Strings

• Throughout this guide we will use the following as our target strings:

STR1 Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)

STR2 Mozilla/4.75 [en](X11;U;Linux2.2.16-22 i586)

Page 40: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

40

Simple Matching

m STR1 match Finds the m in compatible

STR2 no match There is no lower case m in this. Searches are case sensitive.

a/4 STR1 match Found in Mozilla/4.0 - any combination of characters can be used for the match

STR2 match Found in same place as in STR1

5 [ STR1 no match The search is looking for a pattern of '5 [' and this does NOT exist in STR1. Spaces are valid in searches.

STR2 match Found in Mozilla/4.75 [en]

in STR1 match found in Windows

STR2 match Found in Linux

le STR1 match found in compatible

STR2 no match There is an l and an e in this string but they are not adjacent (or contiguous).

Search For

Page 41: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

41

Brackets, Ranges and Negation

Metacharacter Meaning

[ ] Match anything inside the square brackets for one character position once and only once,

i.e. [12] means match the target to either 1 or 2 while [0123456789] means match to any character in the range 0 to 9.

- The - (dash) inside square brackets is the 'range separator' and allows us to define a range, in our example above of [0123456789] we could rewrite it as [0-9].

We can define more than one range inside a list e.g. [0-9A-C] means check for 0 to 9 and A to C (but not a to c).

NOTE: To test for - inside brackets (as a literal) it must come first or last, that is, [-0-9] will test for - and 0 to 9.

^ The ^ (circumflex or caret) inside square brackets negates the expression

i.e. [^Ff] means anything except upper or lower case F and [^a-z] means everything except lower case a to z.

Page 42: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

42

Brackets, Ranges and Negation

in[du] STR1 match finds ind in Windows

STR2 match finds inu in Linux

x[0-9A-Z] STR1 no match The tests are case sensitive to find the xt in DigExt we would need to use [0-9a-z] or [0-9A-Zt]. We can also use this format for testing upper and lower case e.g. [Ff] will check for lower and upper case F.

STR2 match Finds x2 in Linux2

[^A-M]in STR1 match Finds Win in Windows

STR2 no match We have excluded the range A to M in our search so Linux is not found but linux (if present) would be found.

Search For

Page 43: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

43

Positioning (or Anchors)

Metacharacter Meaning

^ The ^ outside square brackets means look only at the beginning of the target string.

i.e. ^Win will not find Windows in STR1 but ^Moz will find Mozilla.

$ The $ (dollar) means look only at the end of the target string, i.e. fox$ will find a match in 'silver fox' but not in 'the fox

jumped over the moon'.

. The . (period) means any character(s) in this position.i.e. ton. will find tons and tonneau but not wanton because it

has no following character.

Page 44: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

44

Positioning (or Anchors)

[a-z]\)$ STR1 matchfinds t) in DigiExt) Note: The \ is an escape characher

and is required to treat the ) as a literal

STR2 no match We have a numeric value at the end of this string but we would need [0-9a-z]) to find it.

.in STR1 match Finds Win in Windows.

STR2 match Finds Lin in Linux.

Search For

Page 45: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

45

Iteration 'metacharacters'

Metacharacter Meaning

? The ? (question mark) matches the preceding character 0 or 1 times onlyi.e., colou?r will find both color and colour.

* The * (asterisk or star) matches the preceding character 0 or more timesi.e., tre* will find tree and tread and trough.

+ The + (plus) matches the previous character 1 or more times.i.e., tre+ will find tree and tread but not trough.

{n} Matches the preceding character n times exactly.i.e., to find a local phone number we could use [0-9]{3}-[0-9]{4} which

would find any number of the form 123-4567.Note: The - (dash) in this case, because it is outside the square brackets,

is a literal. Value is enclosed in braces (curly brackets).

{n,m} Matches the preceding character at least n times but not more than m times.

i.e., 'ba{2,3}b' will find 'baab' and 'baaab' but NOT 'bab' or 'baaaab'. Values are enclosed in braces (curly brackets).

Page 46: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

46

Iteration 'metacharacters'

\(.*l STR1 matchfinds l in compatible (Note: The opening \ is an escape

sequence used to indicate the ( it precedes is a literal not a metacharacter.)

STR2 no match Mozilla contains lls but not preceded by an open parenthesis (no match) and Linux has an upper case L (no match).

W*in STR1 match Finds the Win in Windows.

STR2 match Finds in in Linux preceded by W zero times - so a match.

[xX][0-9a-z]{2} STR1 no match Finds x in DigExt but only one t.

STR2 match Finds X and 11 in X11.

Search For

Page 47: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

47

More 'metacharacters'

Metacharacter Meaning

() The ( (open parenthesis) and ) (close parenthesis) may be used to group (or bind) parts of our search expression together - see this example.

| The | (vertical bar or pipe) is called alternation in techspeak and means find the left hand OR right values, for example, gr(a|e)y will find 'gray' or 'grey'.

Page 48: 1 Javascript Web and Database Management System. 2 Javascript Javascript is a scripting language –There is no need to compile the code before executing

48

Example: More 'metacharacters'

^([L-Z]in) STR1 no matchThe '^' is an anchor indicating first position. Win does not start the string so no match.

STR2 no match The '^' is an anchor indicating first position. Linux does not start the string so no match.

((4\.[0-3])|(2\.[0-3])) STR1 match Finds the 4.0 in Mozilla/4.0.

STR2 match Finds the 2.2 in Linux2.2.16-22.

(W|L)in STR1 match Finds Win in Windows.

STR2 match Finds Lin in Linux.