Slideshow transcript
Slide 1: Ajax 101 Introduction to DHTML & Ajax Development Bill W. Scott,Y! Ajax Evangelist 1
Slide 2: What is Ajax? • AJAX = Asynchronous JavaScript and XML • Strict definition is using XMLHttpRequest (XHR) to retrieve XML within a web page • Ajax = The set of technologies that allow web applications to provide rich interaction, just-in-time information and dynamic interfaces without required page refresh • The Secret Sauce • Ajax = XHR + DHTML (HTML, CSS, JavaScript) + Rich design Ajax 101 2 2
Slide 3: Ajax: Before & After Example Ajax 101 3 3
Slide 4: Classic Web Http Response Server Http Request Ajax 101 4 4
Slide 5: With Ajax Ajax 101 5 5
Slide 6: With Ajax onreadystatechange XHR Server Object send() Ajax 101 5 5
Slide 7: Other Techniques • Hidden IFrame • <img> src • <script> src hack • CSS href hack • JS to faceless Java applets • JS to faceless Flash • NO CONTENT Response • Cookies Ajax 101 6 6
Slide 8: Operation Trigger Update Learning Ajax • Learning Ajax, means understanding • Triggers (event or timer) • Operations (ajax xhr) • Updating (dom) Triggering Using XHR Updating Events & for Ajax the DOM Timers Operations Ajax 101 7 7
Slide 9: Operation. Using XHR Ajax 101 8 8
Slide 10: Ajax Simple Ajax ‘Hello World’ XHR Ajax 101 9 9
Slide 11: Ajax Simple Ajax ‘Hello World’ XHR <h2>Ajax Hello World</h2> <p>Clicking the link below will use XHR to fetch the data and then show the result in the box below.</p> <span class="ajaxlink" onclick="makeRequest('test.xml')"> Make an ajax request for data </span> <div id="helloArea"></div> /index.html Ajax 101 9 9
Slide 12: Ajax Simple Ajax ‘Hello World’ XHR <?xml version="1.0" ?> request <root> XHR This data was brought Object to you by Ajax! data </root> /response.xml response <h2>Ajax Hello World</h2> <p>Clicking the link below will use XHR to fetch the data and then show the result in the box below.</p> <span class="ajaxlink" onclick="makeRequest('test.xml')"> Make an ajax request for data </span> <div id="helloArea"></div> /index.html • Clicking the link makes an XHR request • Response is inserted into the area outlined in blue Ajax 101 9 9
Slide 13: Ajax Ajax How To XHR 1. Create a request object 2. Make the request 3. Handle the response Ajax 101 10 10
Slide 14: Ajax Ajax How To XHR 1. Create a request object request 2. Make the request XHR Object 3. Handle the response response Ajax 101 10 10
Slide 15: 1. Create a Request Object Ajax XHR var xhr = null; if (window.XMLHttpRequest) { browser is mozilla or safari or opera then create a XMLHttpRequest(); xhr = newnew XMLHttpRequest xhr.overrideMimeType(‘text/xml’); otherwise it is IE then } else if (window.ActiveXObject) { create a ActiveXObject(“Microsoft.XMLHTTP”); xhr = newnew ActiveXObject otherwise } else { alert(“Perhaps your browser doesn’t support Ajax.”); error - browser does not support XMLHttpRequest } • IE5, 5.5, 6 implements XHR as an ActiveX object (Msxm12.XMLHTTP/Microsoft.XMLHTTP) • Mozilla 1.0+, Safari 1.2+, Opera 8+, IE7 provide XMLHttpRequest object natively • All XHR objects have same methods & properties Ajax 101 11 11
Slide 16: 1. Create a Request Object Ajax XHR var xhr = null; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); xhr.overrideMimeType(‘text/xml’); } else if (window.ActiveXObject) { xhr = new ActiveXObject(“Microsoft.XMLHTTP”); } else { alert(“Perhaps your browser doesn’t support Ajax.”); } • IE5, 5.5, 6 implements XHR as an ActiveX object (Msxm12.XMLHTTP/Microsoft.XMLHTTP) • Mozilla 1.0+, Safari 1.2+, Opera 8+, IE7 provide XMLHttpRequest object natively • All XHR objects have same methods & properties Ajax 101 11 11
Slide 17: XHR Methods 1. Create Method Description open(“method”, “url”, [, asynchFlag [, Sets up the request object for sending a “username” [, “password”]]]) request send(content) Sends the request to the server. Can be null. abort() Stops the request. getAllResponseHeaders() Returns all response headers for the HTTP request as key/value pairs. getReponseHeader(“header”) Returns the string value of the specified header. setRequestHeader(“header”, “value”) Sets the specified header to the supplied value. Source: Foundations of Ajax - APress Ajax 101 12 12
Slide 18: XHR Properties 1. Create Property Description onreadystatechange The event handler that fires at every state change. readystate The state of the request: 0=uninitialized, 1=loading, 2=loaded, 3=interactive, 4=complete responseText The response from the server as a text string responseXML The response from the server as an XML document status The HTTP status code from the server for the request object: 200: Ok; 201: Created; 400: bad request, 403: Forbidden; 500: internal sever error statusText The text version of the HTTP status code Ajax 101 13 13
Slide 19: 2. Make the Request Ajax XHR set onreadystatechange tohandleAjaxResponse;- handleAjaxResponse xhr.onreadystatechange = callback function open a request ‘response.xml’, xhr.open(‘GET’,on the xhr objecttrue); send the request through the xhr object xhr.send(null); • The JavaScript function handleAjaxResponse will be invoked when the readystate property changes on the XHR object server must be accessible via relative url X • Same site rule response √ • ‘GET’ or ‘POST’ XHR Object • Asynchronous flag request X Ajax 101 14 14
Slide 20: 2. Make the Request Ajax XHR xhr.onreadystatechange = handleAjaxResponse; xhr.open(‘GET’, ‘response.xml’, true); xhr.send(null); • The JavaScript function handleAjaxResponse will be invoked when the readystate property changes on the XHR object server must be accessible via relative url X • Same site rule response √ • ‘GET’ or ‘POST’ XHR Object • Asynchronous flag request X Ajax 101 14 14
Slide 21: Steps 1 & 2:YUI Syntactical Sugar Ajax XHR var request = YAHOO.util.Connect.asyncRequest('GET', ‘response.xml’, { success:handleAjaxResponse, failure:handleFailure }, null); • Callback sets up response • success, failure, timeout callbacks • scope • upload • any user-defined parameters • or just pass a function Ajax 101 15 15
Slide 22: 3. Parse the Response Ajax 4. Response XHR function handleAjaxResponse() handleAjaxResponse { begin if ((xhr.readystate == 4) && (xhr.status == 200)) { response is valid then var doc = xhr.responseXML; get responseXML var rootNode = doc.getElementsByTagName('root').item(0); get var helloArea = document.getElementById("helloArea"); get on the page helloArea.innerHTML=rootNode.firstChild.data; stuff the rootNode value into the helloArea DIV }endif } end • readystate values 0 – Uninitialized 1 – Loading 2 – Loaded 3 – Interactive 4 – Completed Ajax 101 16 16
Slide 23: 3. Parse the Response Ajax 4. Response XHR function handleAjaxResponse() { if ((xhr.readystate == 4) && (xhr.status == 200)) { var doc = xhr.responseXML; var rootNode = doc.getElementsByTagName('root').item(0); var helloArea = document.getElementById("helloArea"); helloArea.innerHTML=rootNode.firstChild.data; } } • readystate values 0 – Uninitialized 1 – Loading 2 – Loaded 3 – Interactive 4 – Completed Ajax 101 16 16
Slide 24: Step 3 with YUI Connection Manager Ajax XHR function handleAjaxResponse(response, callbackObj) { var doc = response.responseXML; var rootNode = doc.getElementsByTagName('root').item(0); var helloArea = document.getElementById("helloArea"); helloArea.innerHTML=rootNode.firstChild.data; } Ajax 101 17 17
Slide 25: 3. Parse the Response: Handling an XML Response on the Client Ajax XHR • Use XHR property responseXML to get the response as an XML DOM (XmlDocument) • Use standard JavaScript DOM methods • Mozilla, Safari, Opera & IE support a common set of methods and properties • Watch out for IE only stuff (e.g., children property) • Watch out for whitespace issues • Other options • Use XML library for JS (e.g., XML for <script>) Ajax 101 18 18
Slide 26: 3. Parse the Response: Xml Document API 4. Response Property/Method Description documentElement Returns the root element of the document firstChild Is the first element within another element (the first child of the current node) lastChild Is the last element within another element (the last child of the current node) nextSibling Is the next element in the same nested level as the current one previousSibling Is the previous element in the same nested level as the current one nodeValue The value of a document element getElementsByTagName Used to place all elements into an object ???????? Ajax 101 19 19
Slide 27: 3. Parse the Response: A little more parsing. 4. Response <?xml version="1.0" ?> <root> <contents> This data was brought to you by Ajax! </contents> <style> height:40px;width:250px;margin-top:20px;padding:20px;border:8px solid red; </style> </root> Ajax 101 20 20
Slide 28: 3. Parse the Response: A little more parsing. 4. Response <?xml version="1.0" ?> <root> <contents> This data was brought to you by Ajax! </contents> <style> height:40px;width:250px;margin-top:20px;padding:20px;border:8px solid red; </style> </root> function handleAjaxResponse() { if (xhr.readyState == 4) { if (xhr.status == 200) { var response = xhr.responseXML.documentElement; var content = response.getElementsByTagName('contents')[0].firstChild.data; var style = response.getElementsByTagName('style')[0].firstChild.data; var helloArea = document.getElementById("helloArea"); helloArea.innerHTML=content; helloArea.style.cssText=style; } else { alert('There was a problem with the request.'); } } } Ajax 101 20 20
Slide 29: 3. Parse the Response: A little more parsing. 4. Response <?xml version="1.0" ?> <root> <contents> This data was brought to you by Ajax! </contents> <style> height:40px;width:250px;margin-top:20px;padding:20px;border:8px solid red; </style> </root> function handleAjaxResponse() { if (xhr.readyState == 4) { if (xhr.status == 200) { var response = xhr.responseXML.documentElement; var content = response.getElementsByTagName('contents')[0].firstChild.data; var style = response.getElementsByTagName('style')[0].firstChild.data; var helloArea = document.getElementById("helloArea"); helloArea.innerHTML=content; helloArea.style.cssText=style; } else { alert('There was a problem with the request.'); } } } Ajax 101 20 20
Slide 30: 3. Parse the Response: A little more parsing. 4. Response <?xml version="1.0" ?> <root> <contents> This data was brought to you by Ajax! </contents> <style> height:40px;width:250px;margin-top:20px;padding:20px;border:8px solid red; </style> </root> function handleAjaxResponse() { if (xhr.readyState == 4) { if (xhr.status == 200) { var response = xhr.responseXML.documentElement; var content = response.getElementsByTagName('contents')[0].firstChild.data; var style = response.getElementsByTagName('style')[0].firstChild.data; var helloArea = document.getElementById("helloArea"); helloArea.innerHTML=content; helloArea.style.cssText=style; } else { alert('There was a problem with the request.'); } } } Ajax 101 20 20
Slide 31: Handling the Response Ajax • Two types: responseText, responseXML XHR • Many forms: data, html, JS, JSON text xml data data html html response XHR Object JS JS request json Ajax 101 21 21
Slide 32: Handling the Response: Server-Side-GUI Method Ajax • JavaScript generated on server-side XHR • JavaScript is eval’ed on client side to generate GUI • Dangerous! text xml data data html html response XHR Object interface JS JS request code json Ajax 101 22 22
Slide 33: Handling the Response: Direct-HTML Method Ajax XHR • HTML generated on server side • Stuffed into innerHTML of DOM element text xml data data html html innerHTML response XHR Object JS JS request json Ajax 101 23 23
Slide 34: Handling the Response: Direct-HTML Method Ajax XHR Ajax 101 24 24
Slide 35: Handling the Response: Direct-HTML Method Ajax XHR // var helloArea = YAHOO.util.Dom.get(“hello-area”); var helloArea = document.getElementById("hello-area"); helloArea.innerHTML=”<p>Hello <em>World</em></p>”; Ajax 101 24 24
Slide 36: Handling the Response: Direct-HTML Method Ajax XHR // var helloArea = YAHOO.util.Dom.get(“hello-area”); var helloArea = document.getElementById("hello-area"); helloArea.innerHTML=”<p>Hello <em>World</em></p>”; <p>A message will be inserted below:</p> <div id=”hello-area” style="height:20px;width: 220px;margin-top:8px;padding:4px;border:1px solid Ajax 101 24 24
Slide 37: Handling the Response: Direct-HTML Method Ajax XHR // var helloArea = YAHOO.util.Dom.get(“hello-area”); var helloArea = document.getElementById("hello-area"); helloArea.innerHTML=”<p>Hello <em>World</em></p>”; <p>A message will be inserted below:</p> <div id=”hello-area” style="height:20px;width: 220px;margin-top:8px;padding:4px;border:1px solid Ajax 101 24 24
Slide 38: Handling the Response:View-From-Model Method Ajax XHR • Model data generated on server side • w3c DOM elements created from model data • Substitute model data into HTML strings and insert via innerHTML text xml data data model html html response XHR Object JS JS request json Ajax 101 25 25
Slide 39: W3C Create Nodes Ajax XHR Ajax 101 26 26
Slide 40: W3C Create Nodes Ajax XHR // var helloArea = YAHOO.util.Dom.get(“hello-area”); var helloArea = document.getElementById("hello-area"); var para = document.createElement("p"); var paraText = document.createTextNode("Hello "); var em = document.createElement("em"); var emText = document.createTextNode("World"); helloArea.appendChild(para); para.appendChild(paraText); para.appendChild(em); em.appendChild(emText); Ajax 101 26 26
Slide 41: W3C Create Nodes Ajax XHR // var helloArea = YAHOO.util.Dom.get(“hello-area”); var helloArea = document.getElementById("hello-area"); var para = document.createElement("p"); var paraText = document.createTextNode("Hello "); var em = document.createElement("em"); var emText = document.createTextNode("World"); helloArea.appendChild(para); para.appendChild(paraText); para.appendChild(em); em.appendChild(emText); <p>A message will be inserted below:</p> <div id=”hello-area” style="height:20px;width: 220px;margin-top:8px;padding:4px;border:1px solid Ajax 101 26 26
Slide 42: W3C Create Nodes Ajax XHR // var helloArea = YAHOO.util.Dom.get(“hello-area”); var helloArea = document.getElementById("hello-area"); var para = document.createElement("p"); var paraText = document.createTextNode("Hello "); var em = document.createElement("em"); var emText = document.createTextNode("World"); helloArea.appendChild(para); para.appendChild(paraText); para.appendChild(em); em.appendChild(emText); <p>A message will be inserted below:</p> <div id=”hello-area” style="height:20px;width: 220px;margin-top:8px;padding:4px;border:1px solid Ajax 101 26 26
Slide 43: Ajax JSON XHR • JavaScript supports several string based notations • Allows the basic types to be represented as string literals • Strings are easy to pass over the wire • JSON (JavaScript Object Notation - json.org) Ajax 101 27 27
Slide 44: JSON Response: Object Literal Ajax XHR {"name": "Jack B. Nimble", "at large": true, "grade": "A", "level": 3} name Jack B. Nimble at large true grade A level 3 Ajax 101 28 28
Slide 45: JSON Response: Array Literal Ajax XHR ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] array of 7 named days [ [0, -1, 0], [1, 0, 0], [0, 0, 1] ] 3x3 array Ajax 101 29 29
Slide 46: JSON Response: JSON is JavaScript Ajax XHR • JSON's simple values are the same as used in JavaScript • No restructuring is requested: JSON's structures are JavaScript! • JSON's object is the JavaScript object • JSON's array is the JavaScript array • Parsing is simple, native Ajax 101 30 30
Slide 47: JSON Response: Parsing JSON Ajax XHR • Obtain responseText • Parse the responseText responseData = eval('(' + responseText + ')'); OR responseData = JSON.parseJSON(responseText); Ajax 101 31 31
Slide 48: JSON Response:Y! JSON API Ajax XHR • http://api.search.yahoo.com/WebSearchService/V1/webSearch? appid=YahooDemo&query=finances&start=1&results=1&output=json { "ResultSet": { "totalResultsAvailable":"69200000", "totalResultsReturned":"1", "firstResultPosition":"1", "Result": { "Title":"Yahoo! Finance", "Summary":"manage the market and your money with Yahoo! Finance. Includes stock market quotes, business news, mutual funds, online bill pay, banking tools, loans, insurance, retirement planning, and tax tips and advice.", "Url":"http://finance.yahoo.com/", "ClickUrl":"http://finance.yahoo.com/", "ModificationDate":"1137225600", "MimeType":"text/html" } } } Ajax 101 32 32
Slide 49: Getting info from a JSON response Ajax XHR http://api.search.yahoo.com/WebSearchService/V1/webSearch? appid=YahooDemo&query=finances&start=1&results=1&output=json Ajax 101 33 33
Slide 50: Getting info from a JSON response Ajax XHR http://api.search.yahoo.com/WebSearchService/V1/webSearch? appid=YahooDemo&query=finances&start=1&results=1&output=json { "ResultSet": { "totalResultsAvailable":"69200000", "totalResultsReturned":"1", "firstResultPosition":"1", "Result": { "Title":"Yahoo! Finance", "Summary":"manage the market and your money with Yahoo! Finance. Includes stock market quotes, business news, mutual funds, online bill pay, banking tools, loans, insurance, retirement planning, and tax tips and advice.", "Url":"http://finance.yahoo.com/", "ClickUrl":"http://finance.yahoo.com/", "ModificationDate":"1137225600", "MimeType":"text/html" } } } Ajax 101 33 33
Slide 51: Getting info from a JSON response Ajax XHR http://api.search.yahoo.com/WebSearchService/V1/webSearch? appid=YahooDemo&query=finances&start=1&results=1&output=json { "ResultSet": { "totalResultsAvailable":"69200000", "totalResultsReturned":"1", "firstResultPosition":"1", "Result": { "Title":"Yahoo! Finance", "Summary":"manage the market and your money with Yahoo! Finance. Includes stock market quotes, business news, mutual funds, online bill pay, banking tools, loans, insurance, retirement planning, and tax tips and advice.", "Url":"http://finance.yahoo.com/", "ClickUrl":"http://finance.yahoo.com/", "ModificationDate":"1137225600", "MimeType":"text/html" } } } responseData = JSON.parseJSON(responseText); var resultsAvail = responseData.ResultSet.totalResultsAvailable; var resultsReturned = responseData.ResultSet.totalResultsReturned; var firstResultTitle = responseData.ResultSet.Result.Title; var firstResultSummary = responseData.ResultSet.Result.Summary; Ajax 101 33 33
Slide 52: Ajax JSON Trip Finder XHR Server XHR Ajax 101 34 34
Slide 53: REST Service Request - Yahoo! Trip Planner - JSON Ajax XHR Yahoo! Trip Planner exposes its service via an URL that requires a free partner key. Notice output=json. http://api.travel.yahoo.com/TripService/V1/tripSearch? appid=PARTNER_KEY&query=alaska&output=json Server XHR Ajax 101 35 35
Slide 54: JSON Response Ajax XHR {"ResultSet":{"firstResultPosition": 1,"totalResultsAvailable":"16","totalResultsReturned": 10,"Result":[ Each response is represented as an object in {"id":"351102","YahooID":"jk_95661","Title":"Cruise with a Y! service responds to Alaska from Vancouver","Summary":"Things to do: Whistler Blackcomb - an array (list) of Hiking,... Hotel: Hyatt Regency Vancouver, Howard JavaScript JSON text string, valid responses Jho...","Destinations":"Vancouver, Anchorage, This is passed object notation. Juneau, North directly back as the XHR Vancouver, Ketchikan, Se...","CreateDate":"1130437928","Duration":"16","Image": result {"Url":"http://us.i1.yimg.com/us.yimg.com/i/travel/tg/ lp/cd/ 100x100_cde24409e413d4d6da27953f6ab0bbde.jpg","Height":"100", "Width":"66"},"Geocode": {"Latitude":"49.284801","Longitude":"-123.120499","precision" :"not available"},"Url":"http://travel.yahoo.com/trip/? pid=351102&action=view"}, {"id":"400333","YahooID":"brdway_grl","Title":"Alaska","Summa ry":"Things to do: Moose's Tooth Pub and Pizzer... Restaurant: Orso, Simon's & Seafort's Salo...","Destinations":"Anchorage","CreateDate":"1134676973" ,"Duration":"10","Image":{"Url":"http://us.i1.yimg.com/ Server us.yimg.com/i/travel/tg/poi/ca/ 100x100_ca605c44b47e20a731d3093b94afa37e.jpg","Height":"75"," Width":"100"},"Geocode": XHR {"Latitude":"61.190361","Longitude":"-149.868484","precision" :"not available"},"Url":"http://travel.yahoo.com/trip/? pid=400333&action=view"}, ... Ajax 101 89 36 36
Slide 55: The Ajax/JSON Code Ajax XHR <script> function showResponse() { if (xhr.readyState == 4) && (xhr.status == 200) { var helloArea = document.getElementById("helloArea"); var theTrip = eval( '(' + xhr.responseText + ')' ); var tripPlanHTML = ""; for(var i=0; i<theTrip.ResultSet.totalResultsReturned; i++) { var result = theTrip.ResultSet.Result[i]; tripPlanHTML = tripPlanHTML + '<div style="padding:4px;border:1px solid gray;width:'+ result.Image.Width+ ';"><img src="'+result.Image.Url+ '" width="'+result.Image.Width+ '" heigh



Add a comment on Slide 1
If you have a SlideShare account, login to comment; else you can comment as a guest- Favorites & Groups
Showing 1-50 of 89 (more)