ajax (asynchronous javascript and xml) 2012. 10 youn-hee han link@koreatech

27
AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH http://link.koreatech.ac.kr

Upload: geraldine-fitzgerald

Post on 18-Dec-2015

223 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

AJAX (Asynchronous JavaScript and

XML)

2012. 10

Youn-Hee HanLINK@KOREATECH

http://link.koreatech.ac.kr

Page 2: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

Ajax - Introduction

What is AJAX?– AJAX = Asynchronous JavaScript and XML

• 웹 브라우저와 웹 서버와의 “ 백그라운드 대화” 를 허용함으로써 보다 동적인 데이터 처리를 가능하게 함

• 전체 페이지를 서버로 부터 가져오기 않고 필요한 데이터만 서버로부터 받아 처리하기 때문에 One-page Web Application 구현이 가능함

LINK@KOREATECH 2

Page 3: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

Ajax Examplegoogle.com Keyword suggestion

LINK@KOREATECH 3

Page 4: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

1. user-driven. Things only happen when the user clicks on a link, pushes a button, etc.

2. 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.

3. 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!)

Characteristics of “classic”

LINK@KOREATECH 4

Page 5: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

4. Synchronous. Things happen / are synchronized with user-driven events.

Characteristics of “classic”

browser

server-side

time

user activity user activity User activity

server processing server processing

Request

Request

Resp

onse

Resp

onse

browser server-side systemshttp request

html + css data

1 2

45

3

1

2

3

4

5

LINK@KOREATECH 5

Page 6: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

browser

From “classic” To “Ajax”

server-side systems

data stores backend etc.U

I

webserver

request

html + css+ xml(or json) data

browser

UIAjax“engine”

JavaScriptcalls

Desktop UI“session” management

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.

How does this work? The next slides explain what’s happing under the “browser hood” to support the Ajax approach.

LINK@KOREATECH 6

Page 7: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

what’s inside a browser so this works?

browser

UI HTML / CSSdata

HTML / CSSdata

other data (e.g. images)

other data (e.g. images)

data

request

HTM

L re

nderi

ng e

ngin

e

browser

UI

rendering engine -- takes HTML/CSS data and images, and ‘knows’ how to format and display it.

Browser knows how to save and manage data it downloads.

What really happens “under the hood” of a “classic” browser.

LINK@KOREATECH 7

Page 8: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

Enter JavaScript (1996-8)

browser

UI

other data (e.g. images)

other data (e.g. images)

HTML / CSSdata

HTML / CSSdata

JavaScript Engine

JavaScriptprograms

JavaScriptprograms

data

HTM

L re

nderi

ng e

ngin

e

Javascript engine – can run programs downloaded alongside the HTML, CSS and images.

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.

LINK@KOREATECH 8

Page 9: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

Ajax: XML data, and a new tool

browser

UI

other data (e.g. images)

other data (e.g. images)

HTML / CSSdata

HTML / CSSdata

JavaScriptprograms

JavaScriptprograms

data

HTM

L re

nderi

ng e

ngin

e

JavaScript Engine

XML (or json)

data

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.

XMLHttpRequest()request

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.

JavaScript programs can now go off and “do their own thing,” including getting data from elsewhere, without waiting for the user to do something!

LINK@KOREATECH 9

Page 10: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

Which brings us to Ajax

Ajax is a pattern for building applications on the browser.

The pattern is:A. 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),

B. 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),

C. Use HTML and CSS for display: manipulate this using JavaScript.

browser

UI

other data (e.g. images)

HTML / CSSdata

XML (or json)data

JavaScriptCode –

the Ajax“engine”

XMLHttpRequest()

HTM

L re

nderi

ng e

ngin

e

JavaScript Engine

A

B

CA

B

C

displayHTML and CSS

Cdata

XML (or json)

BcontrolJavaScript

A

LINK@KOREATECH 10

Page 11: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

Before:

Before and after Ajax

browser

server-side

time

user activity user activity User activity

server processing server processing

Request

Request

Resp

onse

Resp

onse

BrowserUI:

server-side

server processing

Ajax:

time

After:

LINK@KOREATECH 11

Page 12: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han 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 12

Page 13: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han 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 13

Page 14: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

XMLHttpRequest

Create an XMLHttpRequest Object

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");}

LINK@KOREATECH 14

Page 15: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han 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 15

Page 16: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

XMLHttpRequest

Server Response

var obj = eval("(" + xmlhttp.responseText + ")");document.getElementById("myDiv").innerHTML=obj.name;

Property Description

responseText 응답받은 스트링 (json) 형태의 데이터

responseXML 응답받은 XML 형태의 데이터

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;

LINK@KOREATECH 16

<?xml version="1.0" encoding="utf-8"?><ART><ARTIST>James</ARTIST><ARTIST>Ramia</ARTIST><ARTIST>Jone</ARTIST></ART>

{ "name": "Jack B. Nimble", "at large": true, }

Page 17: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

XMLHttpRequest

The onreadystatechange EventProperty Description

onreadystatechange

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

readyState 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

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

LINK@KOREATECH 17

Page 18: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

Ajax Example

Example 1 (1/3)

<html><head><meta charset="utf-8" /><script type="text/javascript">function loadXMLDoc(){ var xmlhttp; if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var xmlDoc = 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; } }

ajaxtest.html

LINK@KOREATECH 18

http://link.koreatech.ac.kr/courses/webservice/ajaxtest.html

Page 19: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

Ajax Example

Example 1 (2/3)

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>

ajaxtest.html

LINK@KOREATECH 19

Page 20: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

Ajax Example

Example 1 (3/3)

<?xml version="1.0" encoding="UTF-8" ?><note>

<to>Steve Jobs</to><from>Michael Jackson</from><body>hello</body>

</note>

note.xml

LINK@KOREATECH 20

Page 21: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

Ajax Example

Example 2 (1/3)<html><head><meta charset="utf-8" /><script type="text/javascript">var xmlhttp;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) { var obj = eval("(" + xmlhttp.responseText + ")"); document.getElementById("myDiv").innerHTML=obj.name; } });}</script></head>

ajaxtest2.html

LINK@KOREATECH 21

http://link.koreatech.ac.kr/courses/webservice/ajaxtest2.html

Page 22: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

Ajax Example

Example 2 (2/3)

<body>

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

</body></html>

ajaxtest2.html

LINK@KOREATECH 22

Page 23: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

Ajax Example

Example 2 (3/3)

{ "name": "Jack B. Nimble", "at large": true, "grade": "A", "format": { "type": "rect", "width": 1920, "height": 1080, "interlace": false, "framerate": 24 }}

note.txt

LINK@KOREATECH 23

Page 24: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

Ajax Example

Example 3 – Ajax with Server-side Scripting Language – http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_databas

e

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 24

Page 25: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

Ajax Security

XMLHttpRequest 의 보안 정책

LINK@KOREATECH 25

Page 26: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han 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 26

Page 27: AJAX (Asynchronous JavaScript and XML) 2012. 10 Youn-Hee Han LINK@KOREATECH

More Ajax Exampleshttp://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 27