[go: up one dir, main page]

0% found this document useful (0 votes)
2 views18 pages

CH12 Ajax

The document provides an overview of AJAX, a technique that allows web pages to be updated asynchronously using XMLHttpRequest, enabling faster and more responsive applications. It explains the process of creating an XMLHttpRequest object, handling server responses, and using methods like load(), get(), and post() for data exchange. Additionally, it includes code examples and references for further learning on AJAX implementation.

Uploaded by

koominjae9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views18 pages

CH12 Ajax

The document provides an overview of AJAX, a technique that allows web pages to be updated asynchronously using XMLHttpRequest, enabling faster and more responsive applications. It explains the process of creating an XMLHttpRequest object, handling server responses, and using methods like load(), get(), and post() for data exchange. Additionally, it includes code examples and references for further learning on AJAX implementation.

Uploaded by

koominjae9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

CAS2109-01 Internet Programming

Spring 2025

AJAX

Yonsei University

“본 강의자료는 연세대학교 학생들을 위해 수업목적으로 제작ㆍ게시된 것이므로


수업목적 외 용도로 사용할 수 없으며, 다른 사람들과 공유할 수 없습니다. 위반에
따른 법적 책임은 행위자 본인에게 있습니다.”
AJAX CAS2109-01

• Not a technology in itself, but a term coined in 2005 by Jesse James


Garrett
• The use of XMLHttpRequest to communicate with servers
• Allows Web pages to be updated asynchronously
• Exchange data with a server behind the scenes
• Update parts of a page without reloading the whole page
• Loads data in the background and display it on the page, without
reloading the whole page
• Makes apps faster and more responsive to user actions

https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX
https://www.w3schools.com/xml/ajax_intro.asp

2
AJAX CAS2109-01

• User fills in a form’s fields, then submits the form


• Browser generates a request to a server
• Server generates/sends a response containing the exact page that
the browser will render
• Browser loads the new page and temporarily makes the browser
window blank
 Client waits for the server to respond and reloads the entire page
with the data from the response

3
AJAX CAS2109-01

Source: Internet & World Wide Web How to Program, 5/e, Pearson
4
AJAX CAS2109-01

• Creates an XMLHttpRequest object to manage a request


• XMLHttpRequest sends the request to and awaits the response
from the server
• Requests are asynchronous
• Allow a user to continue interacting with the application while the
server processes the request concurrently
• When the server responds, XMLHttpRequest invokes a callback
function
• Typically uses partial page updates to display the returned data in
the existing page without reloading the entire page
• Partial page updates help make Web apps more responsive

5
AJAX CAS2109-01

Source: Internet & World Wide Web How to Program, 5/e, Pearson 6
AJAX CAS2109-01

// Immediately Invoked Function Expression

7
AJAX CAS2109-01

동영상

8
AJAX CAS2109-01

https://jsonplaceholder.typicode.com/
9
AJAX CAS2109-01

• Create an XMLHttpRequest object


httpRequest = new XMLHttpRequest();
• Tell the request object which function will handle the response
httpRequest.onreadystatechange = nameOfTheFunction;
// or
httpRequest.onreadystatechange = function(){
// Process the server response here.
};
• Need to actually make the request
httpRequest.open('GET', 'http://www.example.org/some.file', true);
httpRequest.send();
• The parameter to the send() method can be any data you want to
send to the server if POST-ing the request

10
AJAX CAS2109-01

Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
open(method,url,async,user,psw) Specifies the request
method: the request type GET or POST
url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password
send() Sends the request to the server
Used for GET requests
send(string) Sends the request to the server.
Used for POST requests
setRequestHeader() Adds a label/value pair to the header to be sent
getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
abort() Cancels the current request

https://www.w3schools.com/xml/ajax_xmlhttprequest_create.asp 11
AJAX CAS2109-01

Property Description
onreadystatechange Defines a function to be called when the readyState
property changes
The onreadystatechange event is triggered four times (1-
4), one time for each change in the readyState
readyState Holds the status of the XMLHttpRequest
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
responseText Returns the response data as a string
responseXML Returns the response data as XML data
status Returns the status-number of a request
200: "OK"
403: "Forbidden"
404: "Not Found"
For a complete list go to the Http Messages Reference
statusText Returns the status-text (e.g. "OK" or "Not Found")
12
https://www.w3schools.com/xml/ajax_xmlhttprequest_response.asp
AJAX CAS2109-01

• First, the callback function needs to check the request's state


if (httpRequest.readyState === XMLHttpRequest.DONE) { … }
• Next, check the HTTP response status codes of the HTTP response
if (httpRequest.status === 200) {
// Perfect!
} else {
// There was a problem with the request.
// For example, the response may have a 404 (Not Found)
// or 500 (Internal Server Error) response code.
}
• Do whatever you want with the data the server sent: Two options
httpRequest.responseText – returns the response as a string of text
httpRequest.responseXML – returns the response as XMLDocument
• Set header 'Content-Type: application/xml' for IE

13
AJAX CAS2109-01

• Working with the XML response

<h1>The XMLHttpRequest Object</h1>


<button type="button" onclick="loadDoc()">Get my CD collection</button><br><br>
<table id="demo"></table>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) { myFunction(this);}
};
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i, xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" + x[i].getElementsByTagName("ARTIST")[0].firstChild.data +
"</td><td>" + x[i].getElementsByTagName("TITLE")[0].firstChild.data +"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
https://www.w3schools.com/xml/tryit.asp?filename=tryajax_xml2 14
AJAX CAS2109-01

https://www.w3schools.com/xml/cd_catalog.xml 15
AJAX CAS2109-01

• The load() method is a simple but powerful AJAX method


• Loads data from a server and puts the returned data into the
selected element.
$(selector).load(URL, Data, Callback);
• URL(required): specifies the URL you wish to load
• Data(optional): specifies a set of query string key/value pairs to send
along with the request (for POST)
• Callback(optional): the name of a function to be executed after the
load() method is completed

https://www.w3schools.com/jquery/jquery_ajax_load.asp

16
AJAX CAS2109-01

• The $.get() method requests data from a server with GET request:
$.get(URL, callback);
$("button").click(function(){
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);});
});
• The $.post() method requests data from the server using POST:
$.post(URL, data, callback);
$("button").click(function(){
$.post("demo_test_post.asp", {name: "Donald Duck", city: "Duckburg"},
function(data, status){alert("Data: " + data + "\nStatus: " + status);});
});

https://www.w3schools.com/jquery/jquery_ajax_get_post.asp
17
JavaScript CSI-2109-01

• Slides are adapted from the following resource:


• https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX
• www.w3schools.com

18

You might also like