240 likes | 384 Views
CISC 3140 (CIS 20.2) Design & Implementation of Software Application II. Instructor : M. Meyer Email Address: meyer@sci.brooklyn.cuny.edu Course Page: http://www.sci.brooklyn.cuny.edu/~meyer/. Content. XML SAX versus DOM XML-SAX XML-DOM AJAX How it works XMLHttpRequest Object
E N D
CISC 3140 (CIS 20.2)Design & Implementation of Software Application II Instructor : M. Meyer Email Address: meyer@sci.brooklyn.cuny.edu Course Page: http://www.sci.brooklyn.cuny.edu/~meyer/ CISC3140-Meyer-lec8
Content • XML SAX versus DOM • XML-SAX • XML-DOM • AJAX • How it works • XMLHttpRequest Object • XMLHttpRequest.open(…) • Server Response • onreadystatechange Event
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)
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. • We have a parser parse the entire XML document looking for specific "events" or tags. • 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.
More on Parsing <?php $parser=xml_parser_create(); $fp=fopen("test.xml","r"); while ($data=fread($fp, 4096)) { xml_parse($parser, $data,feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser))); } //Free the XML parser xml_parser_free($parser); ?> //Specify element handler xml_set_element_handler($parser, “start", "stop"); //Specify data handler xml_set_character_data_handler($parser, "char"); function char($parser, $data) { echo $data; } function stop($parser,$element_name) { echo "<br>”; } function start($parser, $element_name,$element_attrs) { switch($element_name) . . .
XML-DOM • Where else do we see a Document Object Model? • In the DOM model of XML parsing there are two basic steps that we need to take. • First we parse the entire document and create (in memory) a tree of nodes (objects) based on the XML document. • 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).
Parsed into memory tree <script type="text/javascript"> xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("title")[0]; y=x.childNodes[0].nodeValue; document.write(y); </script>
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.
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
Running 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> http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
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"); }
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();
Details of the open method open( http-method, url, async) • http-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
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
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.
Running 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> http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
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
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: x = xmlhttp.responseText; // This next line changes the html document document.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: 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
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
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: xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }
Running 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> http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first