AJAX - EIE | Homenflaw/EIE4432Sem12018-19/p4s.pdf · AJAX: Asynchronous JavaScript and XML Not a...
Transcript of AJAX - EIE | Homenflaw/EIE4432Sem12018-19/p4s.pdf · AJAX: Asynchronous JavaScript and XML Not a...
1
AJAX
2
3
IntroductionAJAX: Asynchronous JavaScript and XML
Popular in 2005 by GoogleCreate interactive web applications
Exchange small amounts of data with the server behind the scenesNo need to reload the whole page whenever a user requests a change
Asynchronous: loading does not interfere with normal page loading
4
5 6
7
OverviewAJAX: Asynchronous JavaScript and XML
Not a new programming languageUse existing techniques to create better, faster, and interactive web applications
JavaScript + HTML/XHTML/XMLJavaScript: programming language
Communicate with the serverAsynchronous data transfer (HTTP requests) between browser and server
XML:Small bits of information sent between browser and serve
Trades data with a web server without reloading the pageChanges to the underlying data are immediately reflected in the web pageAllow web pages to request small bits of information from the server, instead of whole pages
8
Usage: Live search
9
Usage: voting
10
Overview - techniquesJavaScript + HTML/XHTML/XML
JavaScript:XMLHTTPRequest object communicate with the serverSend HTTP requestReceive HTTP responseHandle the response
Methods:open
Define the method used (GET or POST), URL to send the request, and how the request, whether synchronous or asynchronous, is sent.
sendSends the request to the server
Properties:
11
XMLHttpRequestTwo ways to use the object
Synchronous usageWait for the response, hold processing until a response is received
Asynchronous usageContinue processing, interrupt once a response is received
Security limitations:Can only connect to same domain as currently loaded page (same point of origin)
12
XMLHttpRequest MethodsSending request (asking for data)2 methods:
open(“GET”, “time.php”, true) methodFirst argument: “GET” or “POST”Second argument: URL of the server-side scriptThird argument:
true means that the request should be handled asynchronouslyfalse means that it is a synchronous request
Hold up the processing until a request is receivedsend() method
Sends the request to the server
13
XMLHttpRequestProperties:
onreadystatechangeReturns or sets the event handler for asynchronous requests
readyStateReturns a code representing the state of the request
responseTextReturns the HTTP response as a string
responseXMLReturns the HTTP response as an XML DOM object
statusReturns the HTTP status code
statusTextReturns the text that describes what a particular HTTP status code means
14
onreadystatechangeDefines a function to receive data returned by the server after a request is sentMust be set before sending requestCode:
var xmlhttp = new XMLHttpRequest();xmlHttp.onreadystatechange = myfunction() {
// code for receiving response data}
15
readyStateThis property holds the status of the server’s responseEach time the readyState changes, the onreadystatechangefunction will be executedreadystate Property: state description
0: the request is not initializedObject has been created, but not yet been initialized
1: the request has been set upHas been initialized
2: the request has been sentThe send method has been called, waits for the return of the status code
3: the request is in processSome of the data has been received, but not all
4: the request is complete
16
Update the functionCode:
var xmlhttp = new XMLHttpRequest();xmlHttp.onreadystatechange = myfunction() {
if (xmlhttp.readyState==4) {// code for receiving response data
}}
17
responseText and responseXMLRetrieve data returned by the serverresponseText:
Returns the HTTP response as a stringpText.value = xmlhttp.responseText;
responseXML:Returns the HTTP response as an XML DOM object
Var xmldoc = xmlhttp.responseXML.documentElement;Access it as a DOM document
status: HTTP status code (200, 404, …)
18
Example
19
Basic ProcessDefine an object for sending HTTP requestsInitiate request
Get request objectDesignate a request handler functionInitiate a GET or POST requestSend data
Handle responseWait for readyState==4Extract returned dataProgramme your code for the receiving data
20
Define XMLHttpRequestObject
Different browsers uses different methods to create the XMLHttpRequestobject
Used to communicate with the serverFirefox, IE 7
xmlHttp = XMLHttpRequest();IE 6, IE5
xmlHttp=new ActiveXObject(“Microsoft.XMLHttp");
21
First ExampleIn the body:
<form name="myForm"><label> Name: </label> <input type="text" name="username"
onblur="ajaxFunction()" /></form>
<p name="pText" id="pText"> </p>
22
First Example
head section: function ajaxFunction()
function ajaxFunction() {xmlHttp=null;if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();} else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");}if (xmlHttp != null) {
xmlHttp.onreadystatechange = stateChange;xmlHttp.open("GET", "time.php", true);xmlHttp.send(null);
} else {alert("Your browser does not support XMLHTTP.");
}}
23
First Example
head section: function ajaxFunction()function stateChange() {
if ( (xmlHttp.readyState == 4) &&(xmlHttp.status == 200) ) {pText.innerHTML = "The current time is: " +
xmlHttp.responseText;alert(xmlHttp.responseText);
}}
}
24
First Example: time.php
<?phpecho date("H:i:s");
?>
25
Example 2: Read a textfileUse an XMLHttpRequest to retrieve and display content of a file
26
XML FileXML:
Extensible markup languagePlain textCreate your own tagsDesign to transport and store dataSeparates data from HTML
A start tag and an end tag surrounding the content of an element
<root><child>
<subchild> …. </subchild></child><child> …</child>
</root>
27
Example: BookRoot element: <collection><book>: 3 children: (3 child elements)
<title>, <author>, <year><title> is a start-tag</title> is an end-tag<title> A First Course in Database Systems</title>: is an elementA First course in Database Systems: element content
Code
28
XML Tree
Root element<collection>
Element:<book>
Element:<title>
Element:<author>
Element:<year>
parent child
siblings
Code
29
XML DOMDefines a standard way for accessing and manipulating XML documentsDOM:
Views XML documents as a tree-structurexmlDoc.getElementsByTagName(“xmlname”)[0].childNodes[0].nodeValue
30
Book.xml
getElementsByTagName("title")[0]<title> A First … </title>
getElementsByTagName("title")[0].childNodes[0].nodeValue
A First Course in Database Systems
<book><title> A First Course in Database Systems</title><author> Jeffrey D. Ullman </author><author> Jennifer Widom </author><year> 2002 </year>
</book>
31
Book.xml
getElementsByTagName("author")[0]<author> Jeffrey D. Ullman </author>
getElementsByTagName("author")[1]<author> Jennifer Widom </author>
<book><title> A First Course in Database Systems</title><author> Jeffrey D. Ullman </author><author> Jennifer Widom </author><year> 2002 </year>
</book>
32
AJAX: XML DataUsing responseText:
Example3a.html
divText.innerText = xmlHttp.responseText;
33
AJAX: XML DataUsing responseXML
Parse as XML document (Example3b.html)
tmp = "<table border='1'> ";data = xmlHttp.responseXML.documentElement.
getElementsByTagName("book");for (i=0;i<data.length;i++) {data2 = data[i].getElementsByTagName("title");
tmp = tmp + "<td>" + data2[0].childNodes[0].nodeValue + "</td>";tmp = tmp + "</tr>"
34
ModificationsDisplay author names
35
XMLXML data
Web services use XML to communicateDb sometimes return query as XML
Pros:Human-readable, platform-independentSelf-documenting format
Cons: Bulky syntax, can decrease performance
36
JSON
37
JSONJavaScript Object Notation
Syntax for storing and exchanging text informationUse the build-in JavaScript function eval() to produce JavaScript objects
Cf: XML: use XML DOM to loop through the documentQuicker to read and write
38
Syntax
39 40
AJAX + JSON
function stateChange() {if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var t = eval('('+ xmlHttp.responseText + ')');
divText.innerHTML = t.book[0].title + " " + t.book[0].author;
} }}
41
Concerns“Back” button?Alert users of “background activity”?Reliance on JavaScript
Implemented differently by different browsers
Web statisticsNumber of page loading
42
XMLHttpRequest Level 2
43
Introreadystatechange event:
Lacked a way to communicate upload progress
XMLHttpRequest level 2Introduces progress events
loadstart, progress, abort, error, load, loadend
44
Example<body onload="loadData('BigFile.zip')">
<p id="dData"> </p></body>
var request;var progressBar;function loadData(aFile) {
request = new XMLHttpRequest();request.onloadstart = showProgressBar;request.onprogress = updateProgressBar;request.onloadend = hideProgressBar;request.open("GET", aFile, true);request.send(null);
}
45
function showProgressBar() {progressBar = document.createElement("progress");progressBar.value = 0;progressBar.max = 100;document.body.appendChild(progressBar);
}
function updateProgressBar(e) {if (e.lengthComputable) {
progressBar.value = e.loaded / e.total * 100;dData.innerHTML = progressBar.value + '%';
}}
function hideProgressBar() {document.body.removeChild(progressBar);
}
46
47
SummaryAJAX idea
JavaScript + DataSynchronous vs asynchronous requestPros and cons