web technologies i - sti innsbruck · title. 1. 5. th. march. web engineering introduction and...

Post on 28-May-2020

1 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1© Copyright 2015 Ioan Toma & Srdjan Komazec & Nelia Lassiera

Web Engineering

Web Technologies I

2

Where are we?

# Date Title

1 5th March Web Engineering Introduction and Overview

2 12th March Requirements Engineering for Web Applications

3 19th March Web Application Modeling

4 26th March Web Application Architectures

5 16th April Developing Applications with WebML

6 23rd April Testing and Usability

7 30th April Web Technologies I

8 7th May Web Technologies II

9 21th May Web Application Development Process

10 28th May Project Management for Web Applications

11 11th June Web Application Security

12 18th June Mobile Application Development

13 25th June Final Exam

3

Overview

• Introduction• HTML & XHTML• CSS• JavaScript• AJAX• Summary

4

INTRODUCTIONWhat are the basic ingredients to start to build a Web site

5

Basic Ingredients

• Content structuring (and “basic” presentation…)– (X)HTML

• Business logic (client side)– JavaScript

• Presentation– CSS

• … with these 3 elements you can start building nice (content static) interfaces for you web applications

6

Standards or not Standards?

• XHTML and CSS are W3C recommendations– XHTML 5 (part of HTML5)

• http://www.w3.org/TR/html5/– CSS 3.0

• http://www.w3.org/Style/CSS/

• JavaScript is “not” a standard– This due to the fact that at the beginning there was some competition between Sun

and Microsoft scripting languages– An attempt of standardization was made by European Computer Manufacturers

Association (ECMA), never completed – Latest stable release 1.8.5 (March 2011)– http://en.wikipedia.org/wiki/JavaScript

7

HYPERTEXT MARKUP LANGUAGE

How to structure your content in a Web page

8

HTML & XHTML

• W3C– Set Standards

• Syntax• Functionality

• HyperText Markup Language (v4.01 – 1999)– Type of more general markup language (SGML)– Describes function of text using codes

• Extensible HTML (v5.0 – 2012)– Integrates HTML with XML– Subsumes not only HTML 4, but also XHTML 1 and DOM Level 2 HTML

9

HTML & XHTML

• HTML advantages– Platform portability– Speed (size of file)– Text file

• HTML disadvantages– Rendering differences– Extensions

• Proprietary functionality added by browsers

• XHTML advantages– Resolve issues with different HTML versions

10

Syntax

• Elements (Tags)– Codes that control content appearance– Opening/Closing

• Two-Sided– <tagName>Content</tagName>

• One-Sided– <tagName />

– Lowercase

11

Syntax

• Comments– <!-- . . . -->

• <!-- This is a comment. -->

• White Space– Does not render multiple spaces– Tab and enter do not render– Use non-breaking space

• &nbsp;

• Attributes– Control behavior or appearance of an element

• <tagName attrib#1=“Value” attrib#2=“Value” />

12

<html>

• <html>…</html>– Surrounds all markup & text– Required – Used to begin & end every HTML document

13

<head>

• <head>…</head>– Contains the document's header information– Required – Important information

• Document title• META Tags

– Included text does not render

14

<body>

• <body>…</body>– Contains all content to be rendered

• Attributes– leftmargin=number

• Sets the left margin for page– topmargin=number

• Sets the top margin for the page

15

<body>

• Styles– style=“color: colorName | #rrggbb | rgb(#,#,#);”

• Specifies the color of the regular text

– style=“background-color: colorName | #rrggbb | rgb(#,#,#);”• Specifies the background color

– style=“background-image: url(filename.ext);”• Points to location of image that is used as background• Image is tiled

16

<body>

• Styles– style=“background-position: horizontal vertical;”

• Specifies the positioning of the background image• Can be specified in keywords or percentages

– style=“background-repeat: repeat | repeat-x | repeat-y | no-repeat;”• Specifies the tiling of the background image

– style=“background-attachment: scroll | fixed;”• Background image scrolls with page or acts as watermark

17

<h#>

• <h#>…</h#>– Creates a heading– Numbered from h1 through h6

• h1 is the top head level while h6 is the bottom– Should not be used for text formatting– Conveys page & content organization– Should be used in descending order

• Style– style=“text-align: left | center | right | justify;”

• Specifies the alignment of the heading text

18

<p> & <br>

• <p>…</p>– Inserts blank line before tag

• Separates paragraphs of text

• <br />– Causes text to break wherever tag is placed

19

Lists

• <ul>…</ul>– Unordered list renders a bulleted list– Use when order or rank is unimportant

• Style– style=“list-style-type: disc | square | circle;”

• Changes style of bullet before item

– style=“list-style-image: url(filename.ext);” • Image used as bullet

20

Lists

• <ol>…</ol>– Ordered list tags render a numbered list

• Style– style=“list-style-type: decimal | upper-roman | upper-alpha | . . .;”

• Changes number / letter style before item– style=“list-style-position: inside | outside;”

• Changes wrapped item placement

21

Lists

• <li>…</li>– Defines an item in a list

• <dl>…</dl>– Definition list– <dt>…</dt>

• Defined term– <dd>…</dd>

• Definition

22

Block Level Elements

• <blockquote>…</blockquote>– Content indented on left & right

• <pre>…</pre>– Retains all white space– Uses fixed width typeface

23

Inline Elements

• <strong>…</strong> or <b>…</b>– Bold

• <em>…</em> or <i>…</i>– Italics

• <sub>…</sub>– Subscripted

• <sup>…</sup>– Superscripted

24

Inline Elements

• <span>…</span>– Used for applying CSS classes

• Nesting– Placing sets of tags within each other

• <b><i>…</i></b> instead of <b><i>…</b></i>

25

<img>

• <img />– Inserts an image into a document– Secondary to content

• Attributes– alt=“text”

• Provides alternative text that describes the image• IE displays ALT text when user hovers on image

– Users who surf with graphics turned off– Non-graphical browsers

» Alt text is displayed in place of image

• Required

26

<img>

• Attributes– height=“pixels”

• Specifies the image height– src=“URL”

• Specifies location of image to place in a Web page• Required

– width=“pixels”• Specifies the image width

27

<img>

• Style– style=“float: none | left | right;”

• Place image on left / right & wrap text around it– style=“clear: none | left | right;”

• Display content after margin is clear of floating elements– style=“margin: top# right# bottom# left#;”– style=“border-width: #;”

• Rendered in designated link color if image is a link

28

<hr>

• <hr />– Inserts plain line (horizontal rule) across page– Emphasize divisions & transitions in content

• Style– style=“background-color: #RRGGBB | colorname;”– style=“color: #RRGGBB | colorname;”– style=“height: number;”– style=“width: number;”

29

Special Characters

• &amp; – Ampersand

• &copy;– Copyright

• &middot;– Bullet

• &reg;– Registered

• &trade;– Trademark

30

<a>

• <a>…</a>– Used to create links to other resources– Named anchor

• AKA bookmark• Used to name specific locations within a page• id attribute

– Defines destination

31

<a>

• Attributes– accesskey=“text”

• Character used as keyboard shortcut to activate link– coords=“X1, Y1, X2, Y2, etc.”

• Coordinates that define hot spot shape in image map– href=“URL”

• Specifies location of linked resource– Typically another HTML file– Can also specify other Internet resources

» Files, E-mail, FTP

• Named anchor or bookmark URLs are preceded by #

32

<a>

• Attributes– name=“text”

• Marks specific place within an HTML document• AKA named anchor or bookmark

– rel=“text”• Indicates relationship between documents

– rel=“stylesheet”» Tells browser that linked document is a style sheet

– shape=“rect | circle | poly | default”• Specifies shape of hot spot in image map

33

<a>

• Attributes– title=“text”

• Provides supplemental information regarding a link– Behaves like a Tooltip– Should be less than 60 characters

34

<a>

• Example

<a href="http://www.mysite.com/">A link to a site.</a>

< a href="#P5">A link to paragraph 5 in same document.</a><p>Paragraph 1</p><p>Paragraph 2</p><p>Paragraph 3</p><p>Paragraph 4</p><p id=“P5”>Paragraph 5 content.</p>

35

Paths

• URL (Uniform Resource Locator)– Location of document on the Web

• www.sti-innsbruck.at

• Path– Location of document on a server

• http://www.sti-innsbruck.at/about/team/details/ioan-toma

36

Paths

• Absolute– Exact location on server

• Begins with a /– /student/index.htm

• Relative– Location relative to current document

• Current — Nothing– page.htm

• Child — Separated by /– images/background.gif

• Parent — Two periods (..)– ../page.htm

37

URL

• http://www.sti-innsbruck.at/about/team/details.html

– Communication protocol• http://

– Domain• www.sti-innsbruck.at

– Path • /about/team/

– Document• details.html

38

Protocols

• HyperText Transfer Protocol– Web server– http://

• File Transfer Protocol– File server– ftp://

• USENET– Newsgroup– <a href=“news:newsgroup.name”>Click Me</a>

39

Protocols

• E-Mail

– Mailto• <a href=“mailto:ioan.toma@sti2.at”>Send Mail</a>

– Can automatically include subject line• mailto:ioan.toma@sti2.at?subject=text

– Other options• “mailto:ioan.toma@sti2.at?cc=another@sti2.at

&bcc=secret@cod.edu&subject=subscribe&body=Send me your newsletter right away”

40

<table>

• <table>…</table> – Structure to control page layout– Structure to contain & align content

• Attributes– border=“#”

• Sets thickness of borders displayed for table cells• Attribute set to 0 will make borders “invisible”

41

<table>

• Attributes– cellpadding=“#”

• Specifies amount of space between cell & content in a cell– cellspacing=“#”

• Specifies amount of space between cells– frame=“above | below | border | box | hsides | lhs | rhs | void | vsides”

• Specifies where borders of tables & cells appear

42

<table>

• Attributes– height=“# | %”

• Specifies height of table in pixels or percentage of window– rules=“all | cols | groups | none | rows”

• Specifies where gridlines appear in a table– valign=“top | bottom | middle ”

• Specifies vertical alignment of text in cells– width=“# | %”

• Specifies width of table in pixels or percentage of window

43

<colgroup>

• <colgroup>…</colgroup> – Defines groups of table columns for formatting– Only valid inside <table>

• Attributes– align=“left | center | right | justify | char”

• Specifies horizontal alignment of contents in column group – char=“character”

• Specifies character to use to align text on

44

<colgroup>

• Attributes– span=“#”

• Specifies number of columns <colgroup> should span – valign=“top | middle | bottom | baseline”

• Specifies vertical alignment of contents in <colgroup> – width=“# | %”

• Specifies width of each column in <colgroup>• 0* - column width should be minimum width

45

<col>

• <col /> – Defines one or more columns of table for formatting– Only valid inside <table> or <colgroup>

• Attributes– align=“left | center | right | justify | char”

• Specifies horizontal alignment of contents in table column – char=“character”

• Specifies character to use to align text on

46

<col>

• Attributes– span=“#”

• Specifies number of columns the column should span – valign=“top | middle | bottom | baseline”

• Specifies vertical alignment of contents in table column – width=“# | %”

• Specifies width of column• 0* - column width should be minimum width

47

<tr> & <td>

• <tr>…</tr>– Defines a row in a table

• <td>…</td>– Defines table data (a cell) in a row

• Table data cells must only appear within table rows• Closing tag must appear on same line as content

– Otherwise gapping may occur

48

<td>

• Attributes– colspan=“#”

• Specifies how many columns the cell overlaps– rowspan=“#”

• Specifies how many rows the cell overlaps

49

<th> & <caption>

• <th>…</th>– Specifies the table header for a row

• Identical to table data cells except:– Cells contents are bolded– Cells contents are centered

• <caption>…</caption>– Attaches a caption to a table

50

New HTML5 Elements

• New semantic elements like <header>, <footer>, <article>, and <section>.

• New form control attributes like number, date, time, calendar, and range.

• New graphic elements: <svg> and <canvas>.• New multimedia elements: <audio> and <video>.

51

Elements Removed in HTML5

Element Use instead

<acronym> <abbr>

<applet> <object>

<basefont> CSS

<big> CSS

<center> CSS

<dir> <ul>

<font> CSS

<frame>

<frameset>

<noframes>

<strike> CSS

<tt> CSS

52

New Semantic/Structural Elements

Tag Description<article> Defines an article in the document

<figure> Defines self-contained content, like illustrations, diagrams, photos, code listings, etc.

<footer> Defines a footer for the document or a section<header> Defines a header for the document or a section<main> Defines the main content of a document<section> Defines a section in the document

<menuitem> Defines a command/menu item that the user can invoke from a popup menu

and many more others …

53

New Form Elements and HTML Graphics

Tag Description<datalist> Defines pre-defined options for input controls

<keygen> Defines a key-pair generator field (for forms)

<output> Defines the result of a calculation

Tag Description<canvas> Defines graphic drawing using JavaScript

<svg> Defines graphic drawing using SVG

HTML5 Graphics

New Forms Elements

54

New Media Elements

Tag Description<audio> Defines sound or music content

<embed> Defines containers for external applications (like plug-ins)

<source> Defines sources for <video> and <audio>

<track> Defines tracks for <video> and <audio>

<video> Defines video or movie content

55

CASCADE STYLE SHEETHow to make your Web page good looking

56

History of CSS

• Initial Proposal for CSS – Released in 1994 by Hakon Lie of CERN

• World Wide Web Consortium (W3C)– Founded in 1994 as a Web Standards Organization

• CSS variations• CSS1 - 1996• CSS2 - 1998• CSS2.1 – 2011• CSS3 and CSS4 under development

57

58

CSS Basics

• Style Rules– Determines style characteristics for an HTML element– Selector

• Determines element to which rule is applied– Declaration

• Details the exact property values– Property

» Quality or characteristic (e.g., Color)

– Value» Specification of property (e.g., Blue)

• Style Sheet– Set of Style Rules

59

CSS Basics

• Style rule syntax

60

Combining CSS & HTML

• Inline– Modify the appearance of a particular element

• Style attribute

• Embedded– Applied to an entire document

• Redefines all occurrences of a particular element– Uses <style>…</style> in <head>

• Linked– External file of declarations available to an entire site

• ASCII file with an extension of .css

61

Inline Style

• Defines a style for a single element

– Generally used to override a Style Set at a higher level

– Only affects one instance of an element

• Syntax

– <tag style=“property:value1; property:value2;”>

<h1 style=“color:green; font-family:sans-serif;”>

<b style=“color:yellow; background-color:green;”>

62

Embedded Style

• Always contained in the <head> – Generally used to override a Style Set at a higher level– Only affects the document in which it resides

• Syntax– selector {declarations}

<style type=“text/css”>h1 {color:green; font-family:sans-serif;}b {color:yellow; background-color:green;}

</style>

63

Linked Style

• External Style Sheet– Always contained in the <head>– Text document that contains Style Rules– Allows specification of rules for multiple documents– Does not contain HTML code

• Syntax• <link rel=“stylesheet” href=“master.css” />

64

Cascading

• Determines which rules are assigned to elements

• Assignment weights are based on four variables:– Use of the !Important keyword– Origin of the rule– Specificity of the selector– Order of the rule in the Style Sheet

65

Cascading

• Rule weight with the !Important keyword– Allows user to override author’s style setting

• For particular element

– Improves accessibility of documents • Gives control to users with special requirements

• Rule weight by origin– Cascading order of precedence:

1. Rules from author’s Style Sheet

2. Rules from user’s Style Sheet

3. Rules from browser’s Style Sheet

66

Cascading

• Rule weight by specificity– Rules with more specific selectors take precedence over rules with less specific

selectors

• Rule weight by order– Based on order of rule within Style Sheet

• Rules listed later take precedence over those listed earlier

67

Inheritance

• Parent– Element that contains another element

• Child– Element within another element

• Inheritance– CSS rules inherit from parent to child elements

• Based on hierarchical structure of documents

68

Basic Selection

• Type Selectors– Selector determines element to which declaration is applied– Style Sheet examples:

• h2 {color: red;}• p {font-size: 10 pt;}

69

Basic Selection

• Grouping selectors– Set the same declaration for multiple selectors

• Syntax:

h1 {color: red;}h2 {color: red;}

or

h1, h2 {color: red;}

70

Basic Selection

• Combining Declarations– Multiple declarations may be stated for same selector

• Syntax:

p {color: blue;}p {font-size: 12pt;}

or

p {color: blue; font-size: 12pt;}

71

Basic Selection

• Descendant selector– AKA contextual selectors– Based on hierarchical structure of elements in document

• Syntax:– b i {color: #336699; background-color: #000000;}– Does not apply to i b

72

Advanced Selection

• id attribute selector– Applied to only ONE unique

element in a document– Core attribute that can be applied

to any HTML element

• Syntax:

<p id=“preface”>This is a unique paragraph that is the preface of the document</p>

73

Advanced Selection

• class Attribute Selector– Enables application of rule to selected element(s)– Core attribute that can be applied to any HTML element

• Syntax:<p class=“quote”>Text in red with a 30 pixel margin</p>

– May be restricted to a specific element typeh1.quote {color: red; margin: 30px;}

74

Advanced Selection

• <div>…</div>– Block level element – Used to contain other HTML elements– Displayed discretely from the rest of the document

• Paragraph breaks added before and after <div> contents

• <span>…</span>– Inline element– Used to contain other HTML elements– Used within text blocks

75

Advanced Selection

• Pseudo-Class selectors– Select elements based on characteristics other than name

– Link pseudo-classes

• :link– Allow modification of style characteristics for unvisited links

:link {color: green;}• :visited

– Allow modification of style characteristics for visited links:visited {color: green;}

76

Advanced Selection

• Pseudo-Class selectors– Dynamic pseudo-classes

• Apply styles to an element based on user actions• :hover

– Applies style when user mouses over element• :active

– Applies style when user activates element• :focus

– Applies style when element is accepting user input

77

Fonts

• Measurement units

– Absolute units

• Specify a fixed value

• Cannot be scaled to client display

– Use only when measurements of user medium are known

– Relative units

• Enables scalable web pages

– Adapt to different display types & sizes

– Recommended method for web page design

78

Fonts

• Measurement units

79

Font Propertiess

• Styles

– style=“font-family: fonts;”

• Allows specification of font family names

• Generic font families– Allows greater portability across platforms– Serif → Traditional letter form (e.g., Times)– Sans-serif → Block letters, have no serifs (e.g., Arial)– Monospace → Fixed-width

» Every letter has same horizontal width

– Cursive → Resembles handwriting (Limited Support)– Fantasy → Primarily decorative (Limited Support)

80

Font Properties

• Styles– style=“font-family: fonts;”

• Specific font families– Allows specification of particular font-family

» Garamond, impact

– User must have font installed on machine» If not, browser will supply default

• Example:<p style=“font-family: arial;”>

81

Font Properties

• Styles– style=“font-family: fonts;”

• Specifying font substitution– Allows specification of alternate fonts

» Uses comma separated list

– Browser scans list for first installed font» Otherwise, browser supplies default

– Generic font-family names can be used

• Example:<p style=“font-family: verdana,arial,helvetica,sans-serif;”>

82

Font Properties

• Styles– style=“font-size: size | keyword | %;”

• Absolute keywords– xx-small– x-small– small– medium– large– x-large– xx-large

83

Font Properties

• Styles– style=“font-size: size | keyword | %;”

• Relative keywords– Smaller | Larger– Example

» Parent element’s size is large» Current element’s size is set to larger» Result is that the current font size will be X-large

• Percentage– Example

» 50%, 150%, 200%

84

Font Properties

• Styles– style=“font-style: normal | italic | oblique;”– style=“font-variant: normal | small-caps;”– style=“font-weight: normal | bold | bolder | lighter | #;”

• # = 100 – 900 in increments of 100• 400 = Normal• 700 = Bold

85

Visual Formatting Model

• Three element display type categories– Block (e.g., Paragraphs)

• Contain inline boxes that contain element content

– Inline

• Contain content within the block-level elements

• Do not form new blocks of content

– List-item

• Creates surrounding container and List-item inline boxes

– display: block | inline | list-item | none

86

Box Model

• Describes rectangular boxes that contain content– Each block-level element is displayed as a Box– Each content box can have margins, borders, & padding

87

Margin Properties

• margin: # | %– Shorthand property sets all four individual margins

88

Margin Properties

• margin-left | margin-right | margin-top | margin-bottom: # | %– Negative margins can be set to achieve special effects

89

Padding Properties

• padding: # | %

– Shorthand property sets all four individual paddings

• Same format as margin

• padding-left | padding-right | padding-top | padding-bottom: # | %

90

Border Properties

• border: style width color

– Shorthand property sets all four individual borders

• Same format as margin

91

Border Properties

• border-style: keyword– Keywords

• none• dotted • dashed• solid• double• groove• ridge • inset • outset

92

Border Properties

• border-width: thin | medium | thick | #

• border-color: value

93

Special Box Properties

• width: # | %

– Sets horizontal width of a containing box

• height: # | %

– Sets vertical height of a containing box

• float: left | right | none

– Sets position of an element to left/right of parent element

• clear: none | left | right | both

– Controls flow of text around floated elements

94

Positioning Properties

• position: type position size

– type = static | relative | absolute | fixed

– position = top | left | bottom | right

– size = height | width

95

Positioning Properties

• div {position:absolute; left:130px; top:100px;}

96

Positioning Properties

• div {position:absolute; left:130px; top:100px; width: 100px;}

97

Positioning Properties

• visibility: visible | hidden

– Specifies whether an element is displayed or hidden

• z-index: auto | #

– Specifies an element’s stacking level

98

JAVASCPRIPTHow to add some business logic to your Web page

99

What’s a Scripting Language?

• Language used to write programs that compute inputs to another language processor

– One language embedded in another• Embedded JavaScript computes HTML input to the browser• Shell scripts compute commands executed by the shell

• Common characteristics of scripting languages– String processing – since commands often strings– Simple program structure, define things “on the fly”– Flexibility preferred over efficiency, safety

• Is lack of safety a good thing? (Example: JavaScript used for Web applications…)

100

JavaScript History

• Developed by Brendan Eich at Netscape – Scripting language for Navigator 2

• Later standardized for browser compatibility– ECMAScript Edition 3 (aka JavaScript 1.5)

• Related to Java in name only– Name was part of a marketing deal

• Various implementations available– SpiderMonkey C implementation (from Mozilla)– Rhino Java implementation (also from Mozilla)

101

Common Uses of JavaScript

• Form validation

• Page special effects

• Navigation systems

• Basic math calculations

• Dynamic content manipulation

• Sample applications– Dashboard widgets in Mac OS X, Google Maps, Philips universal remotes, Writely

word processor, hundreds of others…

102

Example 1: Add Two Numbers

<html>…

<p> … </p><script>

var num1, num2, sumnum1 = prompt("Enter first

number")num2 = prompt("Enter second

number")sum = parseInt(num1) +

parseInt(num2)alert("Sum = " + sum)

</script>…

</html>

103

Example 2: Browser Events

<script type="text/JavaScript">function whichButton(event) {

if (event.button==1) {alert("You clicked the left mouse button!") }

else {alert("You clicked the right mouse button!")

}}</script>…<body onmousedown="whichButton(event)">…</body>

Mouse event causes page-defined function to

be called

104

Example 3: Page Manipulation

• Some possibilities– createElement(elementName)– createTextNode(text)– appendChild(newChild)– removeChild(node)

• Example: add a new list itemvar list = document.getElementById('t1')var newitem = document.createElement('li')var newtext = document.createTextNode(text)list.appendChild(newitem)newitem.appendChild(newtext)

105

Language Basics

• JavaScript is case sensitive– onClick, ONCLICK, … are HTML, thus not case-sensitive

• Statements terminated by returns or semi-colons – x = x+1; same as x = x+1

• “Blocks” of statements enclosed in { …}

• Variables– Define using the var statement– Define implicitly by its first use, which must be an assignment

• Implicit definition has global scope, even if occurs in nested scope!

106

JavaScript Primitive Datatypes

• Boolean: true and false

• Number: 64-bit floating point– Similar to Java double and Double – No integer type – Special values NaN (not a number) and Infinity

• String: sequence of zero or more Unicode chars– No separate character type (just strings of length 1)– Literal strings using ' or " characters (must match)

• Special objects: null and undefined

107

Objects

• An object is a collection of named properties

• Think of it as an associative array or hash table– Set of name:value pairs

• objBob = {name: “Bob", grade: 'A', level: 3};– Play a role similar to lists in Lisp / Scheme

• New members can be added at any time• objBob.fullname = 'Robert';

• Can have methods

• Can refer to this

108

Functions

• Functions are objects with method called “( )”– A property of an object may be a function (=method)

• function max(x,y) { if (x>y) return x; else return y;};• max.description = “return the maximum of two arguments”;

– Local declarations may appear in function body

• Call can supply any number of arguments– functionname.length : # of arguments in definition– functionname.arguments.length : # arguments in call– Basic types are passed by value, objects by reference

• “Anonymous” functions – (function (x,y) {return x+y}) (2,3);

109

Examples of Functions

• Curried functionsfunction CurriedAdd(x) { return function(y){ return x+y} };g = CurriedAdd(2);g(3)

• Variable number of argumentsfunction sumAll() {

var total=0;for (var i=0; i< sumAll.arguments.length; i++)

total+=sumAll.arguments[i];return(total); }

sumAll(3,5,3,5,3,2,6)

110

Anonymous Functions

• Anonymous functions very useful for callbacks– setTimeout(function() { alert("done"); }, 10000)– Evaluation of alert("done") delayed until function call

• Simulate blocks by function definition and callvar u = { a:1, b:2 }var v = { a:3, b:4 }(function (x,y) {

var tempA = x.a; var tempB =x.b; // local variablesx.a=y.a; x.b=y.b; y.a=tempA; y.b-tempB

}) (u,v) // Works because objs are passed by ref

111

Basic Object Features

• Use a function to construct an object– function car(make, model, year) {

this.make = make; this.model = model; this.year = year; }

• Objects have prototypes, can be changed– var c = new car(“Ford”,”Taurus”,1988);– car.prototype.print = function () {

return this.year + “ “ + this.make + “ “ + this.model;}– c.print();

112

JavaScript in Web Pages

• Embedded in HTML page as <script> element

– JavaScript written directly inside <script> element• <script> alert("Hello World!") </script>

– Linked file as src attribute of the <script> element• <script type="text/JavaScript" src=“functions.js"></script>

• Event handler attribute• <a href="http://www.yahoo.com " onmouseover="alert('hi');">

• Pseudo-URL referenced by a link• <a href=“JavaScript: alert(‘You clicked’);”>Click me</a>

113

Language Features in This Class

• Stack memory management– Parameters, local variables in activation records

• Garbage collection

• Closures– Function together with environment (global variables)

• Exceptions

• Object features– Dynamic lookup, encapsulation, subtyping, inheritance

• Concurrency

114

JavaScript eval

• Evaluate string as code– The eval function evaluates a string of JavaScript code, in scope of the calling code

var code = "var a = 1";eval(code); // a is now '1‘var obj = new Object(); obj.eval(code); // obj.a is now 1

115

Unusual Features of JavaScript

• Eval, run-time type checking functions

• Support for pattern matching (reg. expressions)

• Can add methods to an object

• Can delete methods of an object– myobj.a = 5; myobj.b = 12; delete myobj.a;

• Iterate over methods of an object– for (variable in object) { statements }

116

JAVASCRIPTFOR MODIFYING HTML

Something we have not seen about it: page manipulation

117

Hello World

<html><body>

<script type="text/javascript">document.write(“<h1>Hello World!</h1>");

</script>

</body></html>

DOM treatment of the page

118

Document URL

<html><body>

The URL of this document is:

<script type="text/javascript">document.write(document.URL);

</script>

</body></html>

119

Form Validation

<html><head>

<script type="text/javascript">function validate() …(next slide)

</script></head>

<body><form action="tryjs_submitpage.htm" onsubmit="return validate()">

Name (max 10 chararcters):<input type="text" id="fname“ size="20"><br />Age (from 1 to 100): <input type="text" id="age" size="20"><br />E-mail: <input type="text" id="email" size="20"><br /><input type="submit" value="Submit">

</form></body></html>

120

Form Validation (Cont.)

<script type="text/javascript">function validate(){

var at=document.getElementById("email").value.indexOf("@");var age=document.getElementById("age").value;var fname=document.getElementById("fname").value;submitOK="true";

if (fname.length>10){alert("The name must be less than 10 characters");submitOK="false"; }

if (isNaN(age)||age<1||age>100) {alert("The age must be a number between 1 and 100");submitOK="false"; }

if (at==-1) {alert("Not a valid e-mail!");submitOK="false"; }

if (submitOK=="false") {return false; }

}</script>

DOM Objects

JavaScript Function

Object Property

121

ASYNCHRONOUS JAVASCRIPT AND XML

Introducing the “push” paradigm in Web applications

122

Where Were We Before AJAX?

• Static pages give the illusion of interactivity through standard form submissions.

• Form submissions result in full page loads.

123

So, What’s The Problem?

• Many actions only manipulate small portions of the page but the entire page must be reloaded.

• Server responses contain the entire page content rather than just the portion being updated.

• Loading entire pages typically results in several additional HTTP requests for images, style sheets, scripts, and any other content that may be on the page.

124

AJAX - Asynchronous JavaScript and XML

• An interface that allows for the HTTP communication without page refreshment.

• Web pages are loaded into an object within the script (e.g., JavaScript) execution and integrated with the page content.

• Thus, the Web page can communicate with the server without refreshing the whole page.

125

Why Use Ajax

• Enhance user experience– Increases usability, speed, interactivity– Makes it possible to update portions of a web page without reloading the entire page– Asynchronous—user does not have to wait for server to respond

126

Real-Life Examples of AJAX Apps

• Google Maps– http://maps.google.com/

• Goolgle Suggest– http://www.google.com/webhp?complete=1&hl=en

• Gmail– http://gmail.com/

• Yahoo Maps (new)– http://maps.yahoo.com/

• Many more…

127

Ajax Example: Google Suggest

• Uses data about the overall popularity of various searches to help rankings

• Does not base suggestions on an individual’s personal search history

128

Why Use Ajax?

• Ajax applications usable on many different– Operating systems– Browsers– Computer architectures

• The web standards that Ajax uses (XHTML, CSS, JavaScript, XML) are well defined, and supported by all major browsers.

129

How Does Ajax Work

• JavaScript communicates directly with the server, using the XMLHttpRequest object (or ActiveXObject)

• Data retrieved from the server can be in a variety of formats: XML, JSON, HTML, text files

130

HTTP Requests: Traditional Model

• Traditional JavaScript:– Make html form

• use GET or POST to communicate with the server – User clicks “Submit” button to send or receive information– User waits

• for the server to respond• for a new page to load with the results

132

Source: http://www.adaptivepath.com/ideas/essays/archives/000385.php

Ajax web application model

Presenter
Presentation Notes
An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by introducing an intermediary — an Ajax engine — between the user and the server. It seems like adding a layer to the application would make it less responsive, but the opposite is true. Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine — written in JavaScript and usually tucked away in a hidden frame. This engine is responsible for both rendering the interface the user sees and communicating with the server on the user’s behalf. The Ajax engine allows the user’s interaction with the application to happen asynchronously — independent of communication with the server. So the user is never staring at a blank browser window and an hourglass icon, waiting around for the server to do something. Every user action that normally would generate an HTTP request takes the form of a JavaScript call to the Ajax engine instead. Any response to a user action that doesn’t require a trip back to the server — such as simple data validation, editing data in memory, and even some navigation — the engine handles on its own. If the engine needs something from the server in order to respond — if it’s submitting data for processing, loading additional interface code, or retrieving new data — the engine makes those requests asynchronously, usually using XML, without stalling a user’s interaction with the application. Source: http://www.adaptivepath.com/ideas/essays/archives/000385.php

133

• JavaScript communicates directly with the server, via the JavaScript XMLHttpRequest object (or ActiveXObject)

• With XMLHttpRequest, the web page can make a request/get a response from web server without reloading

• The user can remain on the same page, not noticing that scripts request pages or send data to a server in the background

HTTP Requests: Using Ajax

134

XMLHttpRequest

• API that JavaScript and other web browser scripting languages use to transfer XML and other data between a web page’s client and server side

• Data returned from XMLHttpRequest calls is often provided by back-end databases.

135

XMLHttpRequest Object History

• Microsoft Internet Explorer version 5– ActiveX object

• Mozilla 1.0 added it as a native object with a compatible API.

• Apple added it to Safari in version 1.2

136

What Technologies Does Ajax Use?

• A combination of:

– XHTML (or HTML)

– Cascading Style Sheets (CSS)

– Document Object Model manipulated using JavaScript to display and interact dynamically with the information presented

– The XMLHttpRequest object to exchange data asynchronously with the web server

137

JavaScript

• Define an object for sending HTTP requests

• Initiate request– Get request object– Designate a response handler function– Initiate a GET or POST request– Send data

• Handle response– Wait for readyState of 4 and HTTP status of 200– Extract return text with responseText or responseXML– Do something with result

• E.g., use innerHTML to insert result into designated element

138

The Server side

• Did we reduce the load on the server?

• Ajax newcomers sometimes mistakenly believe that Ajax, because it provides a more responsive user interface, reduces server-side traffic.

• In fact, Ajax applications typically have more server-side traffic because each Ajax request involves a trip to the server.

– Because those requests are asynchronous, however, Ajax creates the perception of a more responsive UI, though it typically does not reduce the load on the server.

139

So, How Does It Work?

• JavaScript is used to:– Create and control instances of the XMLHttpRequest (XHR) object.– Provide handlers for responses.– Manipulate the DOM.

• The XMLHttpRequest object:– Allows scripts to perform HTTP client functionality.– Supports GET and POST operations.

140

Launching HTTP Requests

Typically, 3 steps are required:1. Construct and configure an XMLHttpRequest object2. Launch the request3. Process the response

141

Constructing an XMLHttpRequest

For Mozilla:

For Microsoft Explorer:

var request = new XMLHttpRequest();

var request = new ActiveXObject("Microsoft.XMLHTTP");

142

Configuring an XMLHttpRequest

• Method is GET, POST, etc.• URL must be in the domain of the current (or a relative URL), for security

reasons• The false will be discussed later

request.open("method","URL",false)

request.setRequestHeader("header","value")

143

Launching the Request

request.send(content)

• content is the posted in a POST request• content can be "null" or empty

144

Reading the Response

request.responseText

• The response as flat text

request.responseXML

• The response as a (DOM) Document object• Available if response Content-Type is text/XML

request.status request.statusText

request.getAllResponseHeaders()

request.getResponseHeader("header")

145

<html>

<head>

<title>Jokes</title>

<script type="text/javascript">

... 2 slides ahead ...

</script>

</head>

An Example

146

<body onload="init(); setJoke()">

<h1>Select a Joke:</h1>

<p><select onchange="setJoke(value)">

<option value="1" selected="selected">Joke 1</option>

<option value="2">Joke 2</option>

<option value="3">Joke 3</option>

</select></p>

<div id="jokediv"></div>

</body>

</html>

An Example (Cont.)

147

<script type="text/javascript">

var jDiv;

function init() { jDiv = document.getElementById("jokediv");}

function setJoke(value) {

request = new XMLHttpRequest();

request.open("GET","joke"+value+".txt",false);

request.send(null);

if(request.status==200){jDiv.innerHTML=request.responseText;}

else {jDiv.innerHTML = "<i>Cannot load joke...</i>";}

}

</script>What if we didn’t get yet the

response in this stage?

An Example (Cont.)

148

Example (Cont.)

• Our examples use “false" in the third parameter of open().– This parameter specifies whether the request should be handled asynchronously.

• True means that the script continues to run after the send() method, without waiting for a response from the server.

149

Asynchronous Requests

• Reading of a Web page can take a long time during which the browser is blocked

• Solution: launch the request asynchronously

• That is, the execution continues after send is called without waiting for it to complete

• When the request is completed, a predefined function is called

request.open("method","URL",true)

150

XMLHttpRequest States

• The XMLHttpRequest goes through several states:

• In the request configuration, you can define a function to call upon state change:

0 not initialized 1 loading 2 loaded

3 interactive 4 complete

request.onreadystatechange = functionName

151

XMLHttpRequest States (Cont.)

• Use request.readyState to get the current state of the request

• Use request.abort() to stop the request

152

var request;

function setJoke(value) {

request = new XMLHttpRequest();

request.open("GET","joke"+value+".txt",true);

request.onreadystatechange = updateJokeDiv;

request.send(null);

}

Asynchronous Example

153

An Example (Cont.)

function updateJokeDiv() {

if(request.readyState<4) {

jokeDiv.innerHTML = "<i>Loading...</i>";

return;

}

if(request.status==200) {

jokeDiv.innerHTML = request.responseText;

} else {

jokeDiv.innerHTML = "<i>Cannot load joke!</i>";

}

}

154

Integrating AJAX and XML using DOM

• The next example shows how XML data can be parsed and added into the content of your page

155

XML+AJAX Example

<html>

<head><title>Country List</title>

<script type="text/javascript">

</script>

</head>

<body onload="init();loadCountries()">

<h1>Select a Continent:</h1>

156

XML+AJAX Example (Cont.)

<p>

<select id="continenetList“onchange="loadCountries()">

<option value="asia">Asia</option>

<option value="africa">Africa</option>

<option value="europe">Europe</option>

</select>

</p>

<p><select size="10" id="countryList"></select></p>

</body>

</html>

157

XML+AJAX Example (Cont.)

function init() {

continents = document.getElementById("continenetList");

countries = document.getElementById("countryList"); }

function loadCountries() {

var xmlURL = "countries-"+continents.value+".xml";

var request = new XMLHttpRequest();

request.onreadystatechange = updateCountries ();

request.open("GET",xmlURL,true);

request.send(null); }

158

XML+AJAX Example (Cont.)

function updateCountries() {

if(request.readyState==4) {

while(countries.length>0){countries.remove(0);}

if(request.status==200) {

var names = request.responseXML.getElementsByTagName("name");

for(var i=0; i<names.length; ++i) {

option = document.createElement("option");option.text=option.value=

names[i].firstChild.nodeValue;countries.appendChild(option);

}}

}

}

159

AJAX: Potential Drawbacks

• "Back" function of browser might not work as expected

• Bookmarking a particular state of the application

• Navigation may be difficult

• User might not notice when small parts of the page change

• Search engine tracking

• If user disables JavaScript

• Many web analytics programs may not track Ajax actions as they do page reloads

Presenter
Presentation Notes
Google map use IFRAMEs

160

WRAP-UPThat’s almost all for day…

161

Things to keep in mind(or summary)

• XHTML for content structure

• CSS for presentation

• JavaScript for client side logic

• Ajax enables asynchronous communication between browser and server

162

Bibliography

• Mandatory reading– XHTML Specification

• http://www.w3.org/TR/xhtml11/– CSS Specification

• http://www.w3.org/TR/CSS2/– JavaScript reference

• http://www.w3schools.com/jsref/default.asp– W3Schools Ajax Tutorial

http://www.w3schools.com/Ajax/Default.Asp

163

Validation Tools

• XHTML– http://validator.w3.org/

• CSS– http://jigsaw.w3.org/css-validator/

164

Next lecture

# Date Title

1 5th March Web Engineering Introduction and Overview

2 12th March Requirements Engineering for Web Applications

3 19th March Web Application Modeling

4 26th March Web Application Architectures

5 16th April Developing Applications with WebML

6 23rd April Testing and Usability

7 30th April Web Technologies I

8 7th May Web Technologies II

9 21th May Web Application Development Process

10 28th May Project Management for Web Applications

11 11th June Web Application Security

12 18th June Mobile Application Development

13 25th June Final Exam

165

Questions?

top related