CISC 3140 (CIS 20.2) Design & Implementation of Software Application II Instructor : M. Meyer Email...

23
CISC 3140 (CIS 20.2) Design & Implementation of Software Application II Instructor : M. Meyer Email Address: [email protected] Course Page: http://www.sci.brooklyn.cuny.edu/~ meyer/ CISC3140-Meyer- lec8 1

Transcript of CISC 3140 (CIS 20.2) Design & Implementation of Software Application II Instructor : M. Meyer Email...

CISC 3140 (CIS 20.2)Design & Implementation of Software Application IIInstructor : M. MeyerEmail Address: [email protected] Page: http://www.sci.brooklyn.cuny.edu/~meyer/

CISC3140-Meyer-lec8

1

Content

•XML SAX versus DOM▫XML-SAX▫XML-DOM

• AJAX• How it works• XMLHttpRequest Object• XMLHttpRequest.open(…)• Server Response• onreadystatechange Event

CISC3140-Meyer-lec8

2

SAX Versus DOM• In our last lecture we examined the basics of XML documents

and how they are "self-describing" data structures:<?xml version="1.0" encoding="ISO-8859-1"?><bookstore>

<book category="non-fiction"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00<price>

</book> </bookstore>

• We need to be able to retrieve information from XML documents.

• There are two different methods for retrieving information from XML documents in their native form (without transferring them to an RDBMS):▫ SAX (Simple API for XML) also called the "Event-Driven" Model▫ DOM (Document Object Model)

CISC3140-Meyer-lec8

3

XML – SAX ( PHP XML Expat Parser )• In the Event-Driven (SAX) model

of XML parsing there are two basic steps that we need to take. 1. We have a parser parse the

entire XML document looking for specific "events" or tags.

2. We have the parser call functions to run when specific events are encountered.

• Advantages: This method is fast for single queries and transformations and uses very little memory!

• Disadvantages: This method it is slow under repeated queries (each pass is a full DFS of the document and is cumbersome.

CISC3140-Meyer-lec8

4

XML-DOM• In the DOM model of XML

parsing there are two basic steps that we need to take. 1. First we parse the entire

document and create (in memory) a tree of nodes (objects) based on the XML document.

2. We can then search only the parts of the tree we are interested in using node relationships to limit our search.

• Advantages: This method is much simpler, more intuitive, and can support high level query languages like XPath and XQuery.

• Disadvantages: This method uses a LOT of memory!!! (2-5 times document size ... at this time).

CISC3140-Meyer-lec8

5

<script type="text/javascript">

xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0];y=x.childNodes[0].nodeValue;document.write(y);

</script>

CISC3140-Meyer-lec8

6

Parsed into memory tree

AJAX•Asynchronous JavaScript and XML. •AJAX is not a new programming language,

but a new way to use existing standards.•AJAX is the art of exchanging data with a

server, and updating only parts of a web page - without reloading the whole page.

•Web pages which do not use AJAX must reload the entire page if the content change.

•Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

CISC3140-Meyer-lec8

7

How AJAX works

CISC3140-Meyer-lec8

8

AJAX uses existing standards

• AJAX is based on internet standards, and uses a combination of:▫ XMLHttpRequest object (to exchange data

asynchronously with a server)▫JavaScript/DOM (to display/interact with the

information)▫CSS (to style the data)▫XML (often as a format for transferring data)

•AJAX applications are browser- and platform-independent

CISC3140-Meyer-lec8

9

Starting Example<html> <head> <script type="text/javascript">

function loadXMLDoc() {var xmlhttp =new XMLHttpRequest(); // code most browsers

xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) {

document.getElementById("myDiv").innerHTML=xmlhttp.responseText; }

}xmlhttp.open("GET","ajax_info.txt",true);xmlhttp.send();

}</script> </head> <body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div><button type="button" onclick="loadXMLDoc()">Change

Content</button></body></html>// Link is here: http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first

CISC3140-Meyer-lec8

10

XMLHttpRequest Object• The XMLHttpRequest object is used to exchange

data with a server behind the scenes. ▫This means that it is possible to update parts of

a web page, without reloading the whole page.• All modern browsers (IE7+, Firefox, Chrome,

Opera) support the XMLHttpRequest object.▫Older Microsoft browsers (IE5 and IE6) use an

ActiveXObject▫Workaround code is relatively easy.

var xmlhttp;if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();} else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}

CISC3140-Meyer-lec8

11

XMLHttpRequest Object (cont)

•Once we have create our XMLHttpRequest object we need to configure it so that it can be used to communicate with the server.

•To send a request to a server, we use the open() and send() methods:

xmlhttp.open("GET","ajax_info.txt",true);xmlhttp.send();

CISC3140-Meyer-lec8

12

Details of the open method open( http-method, url, async)•method,

▫GET or POST▫GET is simpler and faster than POST, and

can be used in most cases. ▫Use POST requests when:

A cached file is not an option Sending a large amount of data to the server

(POST has no size limitations) Sending user input (unknown characters),

POST is more robust and secure than GET

CISC3140-Meyer-lec8

13

Details of the open method open( http-method, url, async)• url is an address • url can be FQDN or relative reference• End of url can be • any kind of file• like .txt and .xml

• server scripting files • like .asp and .php • serve side scripting files can perform actions on

the server including processing user generated input before sending the response back

CISC3140-Meyer-lec8

14

Details of the open method open( http-method, url, async)• async == Asynchronous? (True or False)

▫In order for an XMLHttpRequest object to behave as AJAX, the async parameter has to be true

▫With AJAX, the JavaScript does not have to wait for the server response, but can instead execute other scripts while waiting for response.

▫Using async=false is not recommended, but for a few small requests this can be ok. Remember that JavaScript will NOT continue to

execute, until the server response is ready. If server is busy or slow, the application will hang or stop.

CISC3140-Meyer-lec8

15

Server Response

• To get the response from a server, use the responseText or responseXML property of the XMLHttpRequest object.

▫responseText : get the response data as a string

▫responseXML: get the response data as XML data

CISC3140-Meyer-lec8

16

responseText

• If the response from the server is not XML, use the responseText property • The responseText property returns the

response as a string, and you can use it accordingly:

CISC3140-Meyer-lec8

17

x = xmlhttp.responseText;// This next line changes the html documentdocument.getElementById("myDiv").innerHTML = x;

responseXML

• If the response from the server is XML, and you want to parse it as an XML object, use the responseXML property:

CISC3140-Meyer-lec8

18

xmlDoc = xmlhttp.responseXML;txt="";x = xmlDoc.getElementsByTagName("title");

for (i=0;i<x.length;i++) {  txt=txt + x[i].childNodes[0].nodeValue + "<br />";}

document.getElementById("myDiv").innerHTML=txt;

onreadystatechange Event

• When a request to a server is sent, we want to perform some actions based on the response. The onreadystatechange event-listener is triggered every time the readyState changes.• The readyState property holds the status of

the XMLHttpRequest• onreadystatechange: Stores a function (or the

name of a function) to be called automatically each time the readyState property changes

CISC3140-Meyer-lec8

19

readyState & Status Codes• readyState

▫Holds the status of the XMLHttpRequest. Changes from 0 to 4:

0: request not initialized 1: server connection established2: request received 3: processing request 4: request finished and response is ready

• status▫200: "OK"▫404: Page not found

CISC3140-Meyer-lec8

20

onreadystatechange Event-Listener• In the onreadystatechange event-listener, we

specify what will happen when the ready state status is changed (it will change at least 4 times)

•When readyState is 4 and status is 200, the response is ready:

CISC3140-Meyer-lec8

21

xmlhttp.onreadystatechange = function() {

  if (xmlhttp.readyState==4 && xmlhttp.status==200) {    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;    }}

Sources•Lab 8 will give you an opportunity to get

some hands-on experience with AJAX. ▫JavaScript: If you don’t already know

something about Javascript, then you should run through the basics of the w3schools’ Javascript tutorial. Go to http://www.w3schools.com/js/

▫XML DOM: If you don’t already know something about XML and the DOM of accessing XML, then you should run through the basics of this technology. Go to http://www.w3schools.com/dom

CISC3140-Meyer-lec8

22

You got this!

CISC3140-Meyer-lec8

23