270 likes | 297 Views
AJAX (Asynchronous JavaScript and XML). 2012. 10 Youn-Hee Han LINK@KOREATECH http://link.koreatech.ac.kr. Ajax - Introduction. What is AJAX? AJAX = Asynchronous JavaScript and XML 웹 브라우저와 웹 서버와의 “ 백그라운드 대화 ” 를 허용함으로써 보다 동적인 데이터 처리를 가능하게 함
E N D
AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH http://link.koreatech.ac.kr
Ajax - Introduction • What is AJAX? • AJAX = Asynchronous JavaScript and XML • 웹 브라우저와 웹 서버와의 “백그라운드 대화”를 허용함으로써 보다 동적인 데이터 처리를 가능하게 함 • 전체 페이지를 서버로 부터 가져오기 않고 필요한 데이터만 서버로부터 받아 처리하기 때문에 One-page WebApplication 구현이 가능함 LINK@KOREATECH
Ajax Example • google.com • Keyword suggestion LINK@KOREATECH
Characteristics of “classic” • user-driven.Things only happen when the user clicks on a link, pushes a button, etc. • views defined by address / link. You can bookmark something and come back to it - e.g. http://www.bmo.com-- or use forward/backward button. • simple user interaction.The user – browser interaction is very simple: not like the complex UIs in apps like Word, PowerPoint(of course, that is oftena good thing!) LINK@KOREATECH
1 5 2 4 3 server-side systems browser 1 2 http request 4 html + css data 3 5 Characteristics of “classic” • Synchronous.Things happen / are synchronized with user-driven events. browser user activity user activity User activity time Response Response Request Request server-side server processing server processing LINK@KOREATECH
browser JavaScript calls UI Ajax “engine” + xml(or json) data Desktop UI“session” management From “classic” To “Ajax” Ajax adds an extra layer of functionality on the browser, which helps manage the desktop / user interaction, and intermediates between what the user sees/does and the functionality of – and data sent out by – the server. server-side systems browser web server data stores backend etc. request UI html + css How does this work? The next slides explain what’s happing under the “browser hood” to support the Ajax approach. LINK@KOREATECH
rendering engine -- takes HTML/CSS data and images, and ‘knows’ how to format and display it. browser request UI browser HTML / CSS data UI HTML rendering engine data other data (e.g. images) Browser knows how to save and manage data it downloads. what’s inside a browser so this works? What really happens “under the hood” of a “classic” browser. LINK@KOREATECH
JavaScript programs can detect UI events (clicks, etc.) and run code when the user does something: interactivity is programmable. JavaScript programs, via the engine, can access and modify the HTML / CSS data, dynamically changing the UI that’s displayed. Enter JavaScript (1996-8) browser Javascript engine – can run programs downloaded alongside the HTML, CSS and images. UI JavaScript Engine HTML / CSS data JavaScript programs HTML rendering engine data other data (e.g. images) LINK@KOREATECH
A new JavaScript function. This lets JavaScript programs send out requests for data (images, XML, whatever) on their own, without waiting for a user click. request XMLHttpRequest() XML (or json) data XML (or json) data support. Browsers can now store XML (or json) data, and access / manipulate from JavaScript programs via the JavaScript engine. Ajax: XML data, and a new tool browser JavaScript programs can now go off and “do their own thing,” including getting data from elsewhere, without waiting for the user to do something! UI JavaScript Engine HTML / CSS data JavaScript programs HTML rendering engine data other data (e.g. images) LINK@KOREATECH
browser XMLHttpRequest() UI JavaScript Engine A C HTML / CSS data XML (or json) data JavaScript Code – the Ajax “engine” HTML rendering engine B other data (e.g. images) C B A display data control HTML and CSS XML (or json) JavaScript Which brings us to Ajax • Ajax is a pattern for building applications on the browser. • The pattern is: • Use JavaScript to control the show.Use it to asynchronouslyrequest and retrieve data fromremote servers, whenever the program thinks this is a good idea (i.e. not just when the user does something), • Use XML (or Json) to send numerical or text-style data to the browser. Then use JavaScript to extract data from the XML (or Json), • Use HTML and CSS for display: manipulate this using JavaScript. A B C LINK@KOREATECH
browser user activity user activity User activity time Response Response Request Request server-side server processing server processing Before and after Ajax After: Browser UI: Before: Ajax: time server-side server processing LINK@KOREATECH
Ajax - Introduction • Where does AJAX locate? <html> <head> <script type="text/javascript"> function loadXMLDoc() { .... AJAX script goes here ... } </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@KOREATECH
XMLHttpRequest • XMLHttpRequest object is a developer's dream! • XMLHttpRequest • Ajax 요청을 초기화 하고 Ajax 응답을 처리하는 빌트인 객체 • it is used to exchange data with a server behind the scenes. • With XMLHttpRequest, you can • Update a web page without reloading the entire page • Request data from a server after the page has loaded and rendered • Receive data from a server after the page has loaded and rendered • Send data to a server in the background LINK@KOREATECH
XMLHttpRequest • Create an XMLHttpRequest Object varxmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } LINK@KOREATECH
XMLHttpRequest • Send a Request To a Server • open(method, url, async) • method: 요청 타입 (GET or POST) • url: 요청 url • async: true(asynchronous) or false(synchronous) • send(string) • string: POST 요청에 쓰임 • GET 요청일 경우에는 string은 요구되지 않음 xmlhttp.open("GET", "ajax_info.txt", true);xmlhttp.send(); LINK@KOREATECH
XMLHttpRequest • Server Response varobj = eval("(" + xmlhttp.responseText + ")"); document.getElementById("myDiv").innerHTML=obj.name; { "name": "Jack B. Nimble", "at large": true, } xmlDoc=xmlhttp.responseXML;txt="";x=xmlDoc.getElementsByTagName("ARTIST");for (i=0; i<x.length; i++) { txt=txt + x[i].childNodes[0].nodeValue + "<br />";}document.getElementById("myDiv").innerHTML=txt; <?xml version="1.0" encoding="utf-8"?> <ART> <ARTIST>James</ARTIST> <ARTIST>Ramia</ARTIST> <ARTIST>Jone</ARTIST> </ART> LINK@KOREATECH
XMLHttpRequest • The onreadystatechange Event xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; }} LINK@KOREATECH
http://link.koreatech.ac.kr/courses/webservice/ajaxtest.html Ajax Example • Example 1 (1/3) ajaxtest.html <html> <head> <meta charset="utf-8" /> <script type="text/javascript"> function loadXMLDoc(){ varxmlhttp; if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { varxmlDoc = xmlhttp.responseXML; document.getElementById("to").innerHTML= xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue; document.getElementById("from").innerHTML= xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue; document.getElementById("message").innerHTML= xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue; } } LINK@KOREATECH
Ajax Example • Example 1 (2/3) ajaxtest.html xmlhttp.open("GET", "note.xml", true); xmlhttp.send(); } </script> </head> <body> <h1>Ajax Example</h1> <div> <b>To:</b> <span id="to"></span><br /> <b>From:</b> <span id="from"></span><br /> <b>Message:</b> <span id="message"></span> </div> <p> <button type="button" onclick="loadXMLDoc()">Change Content</button> </p> </body> </html> LINK@KOREATECH
Ajax Example • Example 1 (3/3) note.xml <?xml version="1.0" encoding="UTF-8" ?> <note> <to>Steve Jobs</to> <from>Michael Jackson</from> <body>hello</body> </note> LINK@KOREATECH
http://link.koreatech.ac.kr/courses/webservice/ajaxtest2.htmlhttp://link.koreatech.ac.kr/courses/webservice/ajaxtest2.html Ajax Example ajaxtest2.html • Example 2 (1/3) <html> <head> <meta charset="utf-8" /> <script type="text/javascript"> varxmlhttp; function loadXMLDoc(url, cfunc) { if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=cfunc; xmlhttp.open("GET", url, true); xmlhttp.send(); } function myFunction() { //callback function loadXMLDoc("note.txt", function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200) { varobj = eval("(" + xmlhttp.responseText + ")"); document.getElementById("myDiv").innerHTML=obj.name; } }); } </script> </head> LINK@KOREATECH
Ajax Example • Example 2 (2/3) ajaxtest2.html <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="myFunction()">Change Content</button> </body> </html> LINK@KOREATECH
Ajax Example • Example 2 (3/3) note.txt { "name": "Jack B. Nimble", "at large": true, "grade": "A", "format": { "type": "rect", "width": 1920, "height": 1080, "interlace": false, "framerate": 24 } } LINK@KOREATECH
Ajax Example • Example 3 – Ajax with Server-side Scripting Language • http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_database • Example 4 – CD list Management • http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_xml2 • http://www.w3schools.com/ajax/cd_catalog.xml LINK@KOREATECH
Ajax Security • XMLHttpRequest의 보안 정책 LINK@KOREATECH
Ajax Security • Cross-domain AJAX • XMLHttpRequest의 보안 정책을 Bypass 하여 임의의 사이트에 접근할 수 있는 AJAX • Cross-domain을 실현하는 방법은 여러 가지가 있지만 서버에 Proxy를 두어서 Javascript에서 임의의 사이트의 리소스를 얻어오는 방법이 가장 많이 활용됨 • Proxy 설치하기 • 참고 사이트 • http://www.daniweb.com/web-development/php/code/216729 • 자신의 웹 사이트 홈 디렉토리에 다음 두 개의 파일을 업로드 하기 • proxy.php • class_http.php • Ajax 에서 임의의 사이트 접근 방법 xmlhttp.open("GET", "proxy.php?proxy_url=" + encodeURIComponent("http://xml or json을 얻을 수 있는 사이트 주소"), true); LINK@KOREATECH
More Ajax Examples • http://docs.google.com • Google docs and spreadsheets --- Group spreadsheet and word processing applications (more services coming) • http://www.ajaxdaddy.com/ • http://sixrevisions.com/ajax/ajax_techniques/ • http://www.google.com/webhp?complete=1&hl=en • Google web help – provides hints as you search • http://weboggle.shackworks.com/ • Web-based version of the game ‘boggle’ • http://www.kayak.com/, http://www.sidestep.com • Travel information aggregator – uses Ajax to aggregate to the browser LINK@KOREATECH