slides

27
1 Trees, the DOM and AJAX

Upload: sampetruda

Post on 09-Dec-2014

838 views

Category:

Documents


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: slides

1

Trees, the DOM and AJAX

Page 2: slides

2

Example Tree

Page 3: slides

3

Formal Definition (from Google’s define:tree)

• In graph theory, a directed acyclic graph (DAG) in which the root node has no parent and every other node has exactly one parent.www.mindspring.com/~scarlson/tc/glossary.htm

• In computer science, a tree is a widely-used computer data structure that emulates a tree structure with a set of linked nodes. Each node has zero or more child nodes, which are below it in the tree.A node that has a child is called the child's parent node. A child has at most one parent; a node without a parent is called the root node (or root). Nodes with no children are called leaf nodes. en.wikipedia.org/wiki/Tree_(computing)

Page 4: slides

4

Uses of Trees• Paragraph Numbering in a Document• Family (aSexual reproduction!)• File system e.g. Unix, Dos• Classification e.g. Linnaeus, Dewey• Hierarchical Database e.g. IBMs MIS, LDAP• Web site structure• Hierarchical Menu• Organisational Hierarchy• Class Hierarchy in Java• Assembly / Part hierarchy• Document Object Model• XML• B-tree for efficient indexing

Page 5: slides

5

Current Node F B

Root A 

Leaf D, E, G, J, K, L 

Non-leaf A, B, C, F, H 

Natural Order A, B, D, E, C, F, G, H, J , K, L

 

Subtree F, G, H, J, K, L 

Level 2 

Tree Terminology

Page 6: slides

6

Legal Numberingin a document

In natural order with A as root

 1          B1.1       D1.2        E2.          C2.1        F2.1.1     G2.1.2     H2.1.2.1  J2.1.2.2  K2.1.2.3  L

Page 7: slides

7

Family Terminology

CurrentNode F B

Parent (at most 1) C

 

Children G, H 

Siblings (none) 

Descendents G, H, J, K, L 

Ancestors C, A 

Node and Descendents

F, G, H, J, K, L

 

Page 8: slides

8

File system

• File system in Unix or Windows– C:\Program Files\eXist\webapp\admin\

admin.xql

• Actually this is a ‘Forest’ of trees, each drive a separate Tree

• Shortcuts (symbolic links in UNIX) cut across this tree structure

Page 9: slides

9

Folder Hierarchy

Page 10: slides

10

Navigation in File System

Relative to F BRoot /

 

Current directory (context)

.

 

First Child G (or ./G) 

Parent .. 

Sibling (none) 

A Cousin ../../B/E 

Absolute Path /A/C/F 

Leaf name File 

Node name Directory or Folder 

Page 11: slides

11

Type (A Kind of) Hierarchyrelative to F

G and H would inherit all the attributes and methods of F and define additional attributes and methods of their own.  A type hierarchy allows sharing of definitions. [see ‘Normalisation’

Easily confused with an Object Hierarchy or Whole/Part hierarchy.

Relative to F B

supertype C  

subtype G, H  

Page 12: slides

12

Object Hierarchy• An object hierarchy supports one or more of a number of kinds of

relationship.

• Containment:  – One object is ‘contained’ within, is a part of,  a parent object.  A containment

relationship is used to move, copy or delete a whole subtree. • Scoping: 

– Names of objects must be unique within some scope. Often these scopes are hierarchical.  The name of a child is unique within the scope of the parent. 

• Delegation:  – A child object delegates responsibility for a property to its parent, and so on up

the hierarchy until an object defines the property.  • Aggregation: 

– A parent object has properties determined by the properties of its children.  For example, the value of the ‘cost’ in a non-leaf would be defined as the sum of cost values over all children, with actual cost values defined at the leaves. Min, max, average are other aggregate relationships.

• Distribution: – A parent property is distributed over the children – for example a budget value

defined in the parent is distributed over the children.

Page 13: slides

13

HTML Document (Object Tree)<html> <head> <title>Sample Document</title> </head> <body> <h1>An HTML Document</h1> <p>This is a <i>simple</i> document. </p> </body> </html>

From Flanagan,D. (2002) JavaScript The Definitive Guide , O’Reilly [on-line]

Page 14: slides

14

Document Object Model Class Tree

From Flanagan,D. (2002) JavaScript The Definitive Guide , O’Reilly [on-line]

Page 15: slides

15

The DOM

logical

physical

conceptual

ECMAScript(Javascript)

Gecko(Firefox)

Object Model:Classes : Element, Text…

Methods: getElementsByTagName()

Java

binding

W3C DOM level 1

PHP

Layout Engines Presto (Opera)

Trident(IE6)

Page 16: slides

16

  XPATH DOM

Declarative Procedural (navigational)

Root /  document

Context Node Current Directory

(self)

.

Local Name n

Child *[1][last()]

n.childNodesn.firstChildn.lastChild

Parent .. f.parentNode

Sibling ../g../*

f.nextSiblingf.previousSibling

Attribute f/@att f.getAttribute(att) 

Locate node by ID //[@id='f1'] document.getElementById('f1') 

Locate nodes by Tag

//img document.getElementsByTagName('img')

Number of nodes in sequence

s.length s.length

Select by predicate [@size= 10 and . ='fred']

Page 17: slides

17

AJAX ZIP decode

• Zip decode (in Firefox)• Backend matches partial zipcode to a database

and returns the data as XML• Script uses AJAX to update the page

dynamically without a full refresh– As digits are entered, code in Javascript makes a

request to the server for the list of matches– The matches are used to update the DOM

Page 18: slides

18

var url = "getZip.php?zipcode="; // The server-side scriptvar http = getHTTPObject(); // create the HTTP Objectvar isWorking = false;

<input type="text" size="5" name="zip" id="zip" onkeyup="getList();" onfocus="getList();" /> function getList() { if (!isWorking && http) { var zipcode = document.getElementById("zip").value; http.open("GET", url + escape(zipcode), true); http.onreadystatechange = updateList; /* this sets the call-back function to be invoked when a response from the HTTP request is returned */ isWorking = true; http.send(null); }}function updateList() { if (http.readyState == 4) { // Use the XML DOM to unpack the zip, city and state values var xmlDocument = http.responseXML; ….}

Create HTTPConnection

On event keyup, call getList()

Get the value in the input field

Open HTTP connection,

calling server script

Call this function when reply

If completed

Get the XML document returned

Page 19: slides

19

Sample returned XML

<?xml version="1.0" standalone="yes"?><result> <zip> <zipcode>95472</zipcode> <city>Sebastopol</city> <state>CA</state> </zip> <zip> <zipcode>95473</zipcode> <city>Sebastopol</city> <state>CA</state> </zip> <zip> <zipcode>95476</zipcode> <city>Sonoma</city> <state>CA</state> </zip></result>

Page 20: slides

20

result

zip

zipcode city state

95472 Sebastopol CA

zip

zipcode city state

95473 Sebastopol CA

document

element

text

tag

Page 21: slides

21

function updateList() { if (http.readyState == 4) { // Use the XML DOM to unpack the zip, city and state values

var xmlDocument = http.responseXML; list = document.createElement('div'); // to hold the tree of results

for (i in xmlDocument.firstChild.childNodes) { var el = xmlDocument.firstChild.childNodes[i]; if (el.nodeName=='zip') { // just the zip tags var zipcode = el.childNodes[0].firstChild.data var city = el.childNodes[1].firstChild.data; var state = el.childNodes[2].firstChild.data; var x = document.createElement('div');

var t = document.createTextNode(zipcode +': ' + city + ', ' + state); x.appendChild(t); list.appendChild(x);

} } var list = document.getElementById('list');

divlist.removeChild(divlist.firstChild); divlist.appendChild(list); isWorking = false;

}}

DOM access in JavaScript

Page 22: slides

22

result

zip

zipcode city state

95472 Sebastopol CA

zip

zipcode city state

95473 Sebastopol CA

XMLDocument

firstChild childNodes[1]

childNodes[0]

firstChild

data

XMLDocument.firstChild .childNodes[1] .childNodes[0] .firstChild .data

Access to nodes

Page 23: slides

23

(document)

html

body

h1 div

head

form

id=‘list’

HTML Document (skeleton)

document.getElementById(‘list’)

Page 24: slides

24

function updateList() { if (http.readyState == 4) {

// Use the XML DOM to unpack the zip, city and state values

var xmlDocument = http.responseXML;

list = document.createElement('div'); // to hold the tree of results for (i in xmlDocument.firstChild.childNodes) { var el = xmlDocument.firstChild.childNodes[i]; if (el.nodeName=='zip') { // just the zip tags var zipcode = el.childNodes[0].firstChild.data var city = el.childNodes[1].firstChild.data; var state = el.childNodes[2].firstChild.data;

var x = document.createElement('div'); var t = document.createTextNode(zipcode +': ' + city + ', ' + state); x.appendChild(t); list.appendChild(x); } } var divlist = document.getElementById('list'); divlist.removeChild(divlist.firstChild); divlist.appendChild(list); isWorking = false;

}}

Page 25: slides

25

div

div

95473: Sebastapol, CA

divdiv

95472: Sebastapol, CA 95474: Sonoma, CA

div

id=‘list’

div

div div

Update the page

var divlist

Page 26: slides

26

Design Issues

• DOM interface not fully supported in IE6 so this code fails – need workarounds for full browser compatibility

• Server could output HTML, then client can just update using innerHTML, but less general

• Multiple concurrent requests possible but complex• Interface no longer behaves like standard page – back

button goes all the way back.• AJAX is at the heart of the browser-as-desktop

applications – Flickr, GoogleMap, Google Suggest.• Security restrictions on the Browser restricts the target of

HTTPXMLRequest calls to the same host as the current page. This is a major restriction on this approach when constructing mashups.

Page 27: slides

27

Tutorial overview

• Test and critique a few AJAX application.

• What are the pluses and minuses about this type of interface?

• What domains are well-handled by tree structures and what are not?