1 trees, the dom and ajax. 2 example tree 3 formal definition (from google’s...

27
1 Trees, the DOM and AJAX

Post on 19-Dec-2015

218 views

Category:

Documents


2 download

TRANSCRIPT

1

Trees, the DOM and AJAX

2

Example Tree

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)

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

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

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

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

 

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

9

Folder Hierarchy

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 

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  

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.

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]

14

Document Object Model Class Tree

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

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)

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']

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

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

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>

20

result

zip

zipcode city state

95472 Sebastopol CA

zip

zipcode city state

95473 Sebastopol CA

document

element

text

tag

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

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

23

(document)

html

body

h1 div

head

form

id=‘list’

HTML Document (skeleton)

document.getElementById(‘list’)

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;

}}

25

div

div

95473: Sebastapol, CA

divdiv

95472: Sebastapol, CA 95474: Sonoma, CA

div

id=‘list’

div

div div

Update the page

var divlist

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.

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?