SDPLNotes 3.3: DOM Examples1 3.3 DOM Examples 1. DOM processing in a Web browser –a toy "XML database browser" –with JavaScript and MS Internet Explorer.

Slides:



Advertisements
Similar presentations
SE 5145 – eXtensible Markup Language (XML ) DOM (Document Object Model) (Part II – Java API) /Spring, Bahçeşehir University, Istanbul.
Advertisements

JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
Java Script Session1 INTRODUCTION.
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
The Web Warrior Guide to Web Design Technologies
Chapter 7 © 2001 by Addison Wesley Longman, Inc. 1 Chapter 7 Sebesta: Programming the World Wide Web.
Javascript Document Object Model. How to use JavaScript  JavaScript can be embedded into your html pages in a couple of ways  in elements in both and.
Tutorial 10 Programming with JavaScript
Information Technology Center Hany Abdelwahab Computer Specialist.
Computer Science 103 Chapter 4 Advanced JavaScript.
XP Tutorial 1 New Perspectives on JavaScript, Comprehensive1 Introducing JavaScript Hiding Addresses from Spammers.
Introduction To JavaScript What JavaScript Is: a general purpose scripting language that allows a static page to interact with users and respond to events.
CST JavaScript Validating Form Data with JavaScript.
DHTML. What is DHTML?  DHTML is the combination of several built-in browser features in fourth generation browsers that enable a web page to be more.
JS: DOM Form Form Object Form Object –The Form object represents an HTML form. –For each instance of a tag in an HTML document, a Form object is created.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
HTML DOM.  The HTML DOM defines a standard way for accessing and manipulating HTML documents.  The DOM presents an HTML document as a tree- structure.
JavaScript Defined DOM (Document Object Model) General Syntax Body vs. Head Variables Math & Logic Selection Functions & Events Loops Animation Getting.
SDPL 2002Notes 3.2: Document Object Model1 XML 접근과 관련된 자료.
Adminisztratív November 24.-én az előadás és a gyakorlat elmarad A nagy gyakorlati feladatok beszedése a december 1.-én tartandó gyakorlatra tolódik A.
Event Handlers CS101 Introduction to Computing. Learning Goals Learn about event handlers Determine how events are useful in JavaScript Discover where.
Execution Environment for JavaScript " Java Script Window object represents the window in which the browser displays documents. " The Window object provides.
JavaScript II ECT 270 Robin Burke. Outline JavaScript review Processing Syntax Events and event handling Form validation.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
JavaScript Part 1.
Chapter 3 : Processing on the Front End JavaScript Technically its name is ECMA-262, which refers to the international standard which defines it. The standard.
DHTML: Dynamic HTML Internet Technology1. What is DHTML? A collection of enhancements to HTML ► To create dynamic and interactive websites Combination.
1 rfXcel Confidential Copyright 2007 Web Technology JavaScript 12/10/07.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
3/29/2001 O'Reilly Java Java API for XML Processing 1.1 What’s New Edwin Goei Engineer, Sun Microsystems.
SDPL 2002Notes 3: XML Processor Interfaces1 3. XML Processor APIs n How can applications manipulate structured documents? –An overview of document parser.
Lesson13. JavaScript JavaScript is an interpreted language, designed to function within a web browser. It can also be used on the server.
JavaScript, Fourth Edition
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Tutorial 10 Programming with JavaScript. XP Objectives Learn the history of JavaScript Create a script element Understand basic JavaScript syntax Write.
An Introduction to JavaScript Summarized from Chapter 6 of “Web Programming: Building Internet Applications”, 3 rd Edition.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Javascript II DOM & JSON. In an effort to create increasingly interactive experiences on the web, programmers wanted access to the functionality of browsers.
SDPL 2002Notes 3.2: Document Object Model1 3.2 Document Object Model (DOM) n How to provide uniform access to structured documents in diverse applications.
McGraw-Hill/Irwin © 2004 by The McGraw-Hill Companies, Inc. All rights reserved. Scripting with the DOM Ellen Pearlman Eileen Mullin Programming the Web.
JavaScript - A Web Script Language Fred Durao
JavaScript, jQuery, and Mashups Incorporating JavaScript, jQuery, and other Mashups into existing pages.
Lecture 10 JavaScript: DOM and Dynamic HTML Boriana Koleva Room: C54
JavaScript - Basic Concepts Prepared and Presented by Hienvinh Nguyen, Afshin Tiraie.
Scott Marino MSMIS Summer Session Web Site Design and Authoring Session 8 Scott Marino.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.2 Revised by Dr. T. Tran for CSI3140.
Scripting and Interactivity 이병희
Schema Data Processing
Jaana Holvikivi 1 Introduction to Javascript Jaana Holvikivi Metropolia.
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Variables, Functions and Events (NON-Audio version) © Dr. David C. Gibbs WDMD.
JavaScript Defined DOM (Document Object Model) General Syntax Body vs. Head Variables Math & Logic Selection Functions & Events Loops Animation Getting.
SDPL 2002Notes 3.2: Document Object Model1 The Misconceived Web n The original vision of the WWW was as a hyperlinked document-retrieval system. n It did.
CIS 3.5 Lecture 2.3 "Introduction to JavaScript".
Copyright © Terry Felke-Morris WEB DEVELOPMENT & DESIGN FOUNDATIONS WITH HTML5 7 TH EDITION Chapter 14 Key Concepts 1 Copyright © Terry Felke-Morris.
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
Host Objects: Browsers and the DOM
JavaScript II ECT 270 Robin Burke. Outline Functions Events and event handling Form validation.
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
Chapter 4 Java Script - Part1. 2 Outlines Introduction to Java Script Variables, Operators and Functions Conditional statements JavaScript Objects Forms.
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
JavaScript and AJAX 2nd Edition Tutorial 1 Programming with JavaScript.
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Chapter 5 Host Objects: Browsers.
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
DHTML Javascript Internet Technology.
DHTML Javascript Internet Technology.
CHAPTER 7 JavaScripts & HTML Documents
Introduction to JavaScript
Presentation transcript:

SDPLNotes 3.3: DOM Examples1 3.3 DOM Examples 1. DOM processing in a Web browser –a toy "XML database browser" –with JavaScript and MS Internet Explorer 2. Stand-alone DOM processing –creating and updating XML files –with Java and SUN JAXP implementation of DOM

SDPLNotes 3.3: DOM Examples2 A Very Short Introduction to JavaScript n a simple object-oriented scripting language –for computations in a host environment (e.g. a browser or a server) –depends on host objects for central tasks like input and output –used to manipulate, customise and automate facilities of an existing system n originally a Web scripting language –core language independent of host environments –standardised version called ECMAScript (Aug. 1998)

SDPLNotes 3.3: DOM Examples3 Basic components of JavaScript n Objects: collections of properties: –other objects, primitive values, or methods –Methods: functions associated to an object Primitive values Primitive values –Undefined, Null, numbers (ints and floats) – Strings: "Hi world!", 'Type "Y" for yes' –Booleans true and false »true != 1 and false != 0, but »if (1) and if (2) succeed, while if (0) fails

SDPLNotes 3.3: DOM Examples4 Syntax, data types and variables n JavaScript syntax resembles Java n JavaScript is loosely typed –variables need not be declared; normally created by assigning a value Global and local variables: Global and local variables: function newFunction() { var loop=1; // local variable total=0;// global variable total=0;// global variable...additional statements......additional statements...}

SDPLNotes 3.3: DOM Examples5 Web Scripting in a Browser n The client-side host environment provides –objects for UI components: windows, menus, pop- ups, dialog boxes, text areas, anchors, frames, history, cookies, and input/output – means to attach scripting code to events »actions occurring on the Web page: mouse actions, page and image loading, selection, form submission,… n Scripting code resides in the HTML page –reactive to user interaction; no need for a main program

SDPLNotes 3.3: DOM Examples6 Event Handlers n Scripts normally event-driven, triggered by actions on the Web page n Event handlers attached to elements corresponding to UI objects which notify events: n Events part of the DOM –standardised in DOM Level 2

SDPLNotes 3.3: DOM Examples7 Some Common Events & Handlers click & onClick (on a form element or link) click & onClick (on a form element or link) change & onChange (of text, textarea, or select element) change & onChange (of text, textarea, or select element) focus & onFocus and blur & onBlur : focus & onFocus and blur & onBlur : –input focus given to or removed from a form element load & onLoad and unload & onUnload load & onLoad and unload & onUnload –User loads or exits the page

SDPLNotes 3.3: DOM Examples8 A JavaScript-DOM example n A simple database browser n Technical basis –msxml parser included in MS IE 5 browser –exposes XML documents to JavaScript as a DOM-compliant ActiveX object

SDPLNotes 3.3: DOM Examples9 DOM example: UI frames The UI consists of two HTML frames: one for control buttons, the other for display The UI consists of two HTML frames: one for control buttons, the other for display<HTML><HEAD> XML DOM Database viewer XML DOM Database viewer </HEAD> <!-- 1/3 of width for controls frame and 2/3 for display frame --> controls frame and 2/3 for display frame --> </HTML>

SDPLNotes 3.3: DOM Examples10 The Example Database File <db><personidnum="1234"><last>Kilpeläinen</last><first>Pekka</first></person> <last>Möttönen</last><first>Matti</first></person> >Möttönen</last><first>Maija</first></person> >Römppönen</last><first>Maija</first></person></db>

SDPLNotes 3.3: DOM Examples11 Main data structures (Script begins) In controls.html : In controls.html : <!-- // Script begins; Variables: var xmldoc = new ActiveXObject("Microsoft.XMLDOM"); var xmldoc = new ActiveXObject("Microsoft.XMLDOM"); var displStr; /* string for HTML var displStr; /* string for HTML display of xmldoc */ var current; // index of current row var displayFrame; var persons;/* list of person elements in xmldoc */

SDPLNotes 3.3: DOM Examples12 Body of the controls frame XML DOM Database Viewer XML DOM Database Viewer Enter the location of the XML file: Enter the location of the XML file: <INPUT ID="XMLFile" TYPE="text" SIZE="30" VALUE="db.xml"></INPUT> <INPUT TYPE="button" onClick="loadXML()" VALUE="Load XML and Display DB"> VALUE="Load XML and Display DB"> Refresh Display Refresh Display

SDPLNotes 3.3: DOM Examples13 Controls Frame: navigation buttons <BUTTON OnClick="if (persons==null) alert('Empty database'); else { if ( checkPrev(persons,current) ) showPerson(--current); else alert('At the first person') }"> Previous Person Previous Person <BUTTON OnClick="if (persons==null) alert('Empty database'); else {if ( checkNext(persons,current) ) showPerson(++current); else alert('No more persons') }"> Next Person Next Person

SDPLNotes 3.3: DOM Examples14 Helper functions (Script continues) function initFrames() // on load {displayFrame = parent.display; displayFrame.document.open(); displayFrame.document.write(""); displayFrame.document.close();} function checkPrev(list, index) { return (index > 0); } function checkNext(list, index) { return (index < list.length - 1);} /* DOM Core features emphasised */

SDPLNotes 3.3: DOM Examples15 DB Viewer: XML loading function loadXML(){ … xmldoc.load(XMLFile.value); if (xmldoc.documentElement != null) { persons= xmldoc.getElementsByTagName("person"); current = 0; displayDB();}}

SDPLNotes 3.3: DOM Examples16 Generating the HTML display (1) function displayDB(){ //... // addhtml() collects result to displStr displStr = ""; var rows = xmldoc.documentElement.childNodes; addhtml(' '); addhtml(' '); for (var i = 0; i < rows.length; i++) { // generate HTML for each row; // See loop body below

SDPLNotes 3.3: DOM Examples17 Generating the HTML display (2) var currRow = rows.item(i); addhtml('<TR>'); addhtml(' ' + ((i == current)?'*** ':' ') + ' '); // print stars in front of current addhtml(' ' + currRow.getAttribute("idnum") + ' '); addhtml(' ' + // contents of element ‘last’ currRow.firstChild.firstChild.nodeValue + ' '); addhtml(' ' + // contents of element ‘first’ currRow.lastChild.firstChild.nodeValue + '</TD>'); addhtml(' '); }; // end loop through rows

SDPLNotes 3.3: DOM Examples18 Generating the HTML display (3) // Complete the HTML display: addhtml('</TABLE>');displayFrame.document.open();displayFrame.document.write(displStr);displayFrame.document.close(); } // end displayDB() // Wrapper for displaying current person: function showPerson(pers){ displayDB()// simply display all }

SDPLNotes 3.3: DOM Examples19 A Java-DOM example A stand-alone toy application BuildXml A stand-alone toy application BuildXml –either creates a new db document with two person elements, or adds them to an existing db document –based on the example in Sect. 8.6 of Deitel et al: XML - How to program n Technical basis –DOM support of the Java-based JAXP XML processor implementation –native XML document initialisation and storage methods of the JAXP 1.1 default parser (Apache Crimson)

SDPLNotes 3.3: DOM Examples20 Code of BuildXml (1) n Begin by importing necessary packages: import java.io.*; import org.w3c.dom.*; import org.xml.sax.*; import javax.xml.parsers.*; // Native (parse and write) methods of the // JAXP 1.1 default parser (Apache Crimson): import org.apache.crimson.tree.XmlDocument;

SDPLNotes 3.3: DOM Examples21 Code of BuildXml (2) Class for modifying the document in file fileName : Class for modifying the document in file fileName : public class BuildXml { private Document document; private Document document; public BuildXml(String fileName) { File docFile = new File(fileName); File docFile = new File(fileName); Element root = null; // doc root elemen Element root = null; // doc root elemen // Obtain a SAX-based parser: DocumentBuilderFactory factory = DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance(); DocumentBuilder builder; /* … */ DocumentBuilder builder; /* … */

SDPLNotes 3.3: DOM Examples22 Code of BuildXml (3) (After a succestul try to get a new documentBuilder builder from factory :) if (!docFile.exists()) { //create new doc (After a succestul try to get a new documentBuilder builder from factory :) if (!docFile.exists()) { //create new doc document = builder.newDocument(); document = builder.newDocument(); // add a comment: // add a comment: Comment comment = document.createComment( Comment comment = document.createComment( "A simple personnel list"); "A simple personnel list"); document.appendChild(comment); document.appendChild(comment); // Create the root element: // Create the root element: root = document.createElement("db"); root = document.createElement("db"); document.appendChild(root); document.appendChild(root);

SDPLNotes 3.3: DOM Examples23 Code of BuildXml (4) … or if docFile already exists: } else { // access an existing doc try { // to parse docFile try { // to parse docFile document = builder.parse(docFile); root = document.getDocumentElement(); } catch (SAXException se) { } catch (SAXException se) { System.err.println("Error: " + se.getMessage() ); System.exit(1); } /* A similar catch for a possible IOException */ /* A similar catch for a possible IOException */

SDPLNotes 3.3: DOM Examples24 Code of BuildXml (5) Create and add two child elements to root : Node personNode = createPersonNode(document, "1234", "Pekka", "Kilpeläinen"); Create and add two child elements to root : Node personNode = createPersonNode(document, "1234", "Pekka", "Kilpeläinen"); root.appendChild(personNode); root.appendChild(personNode); personNode = createPersonNode(document, "5678", "Irma", "Könönen"); personNode = createPersonNode(document, "5678", "Irma", "Könönen"); root.appendChild(personNode); root.appendChild(personNode);

SDPLNotes 3.3: DOM Examples25 Code of BuildXml (6) Finally, store the result document: try { // to write the // XML document to file fileName Finally, store the result document: try { // to write the // XML document to file fileName ((XmlDocument) document).write( new FileOutputStream(fileName)); ((XmlDocument) document).write( new FileOutputStream(fileName)); } catch ( IOException ioe ) { } catch ( IOException ioe ) { ioe.printStackTrace(); } ioe.printStackTrace(); }

SDPLNotes 3.3: DOM Examples26 Subroutine to create person elements public Node createPersonNode(Document document, String idNum, String fName, String lName) { Element person = document.createElement("person"); Element person = document.createElement("person"); person.setAttribute("idnum", idNum); person.setAttribute("idnum", idNum); Element firstName = document.createElement("first"); Element firstName = document.createElement("first"); person.appendChild(firstName); firstName.appendChild( document.createTextNode(fName) ); firstName.appendChild( document.createTextNode(fName) ); /* … similarly for a lastName */ /* … similarly for a lastName */ return person; return person;}

SDPLNotes 3.3: DOM Examples27 The main routine for BuildXml public static void main(String args[]){ if (args.length > 0) { String fileName = args[0]; BuildXml buildXml = new BuildXml(fileName); BuildXml buildXml = new BuildXml(fileName); } else { } else { System.err.println( "Give filename as argument"); }; }; } // main

SDPLNotes 3.3: DOM Examples28 Summary of XML APIs n XML processors make the structure and contents of XML documents available to applications through APIs n Event-based APIs –notify application through parsing events –e.g., the SAX callback interfaces n Object-model (or tree) based APIs –provide a full parse tree –e.g, DOM, W3C Recommendation –more convenient, but may require too much resources with the largest documents n Major parsers support both SAX and DOM