Bài giảng Web technologies and e-Services - Bài 10: AJAX - Trường Đại học Bách khoa Hà Nội

AJAX  
Content  
v Basic objects necessary  
v Setting up the XMLHttpRequest object  
v Making the call  
v How the server responds  
v Using the reply  
v XML basics  
The usual way we operate in the Web  
v Typical browsing behaviour consists of loading a web page,  
then selecting some action that we want to do, filling out a  
form, submitting the information, etc.  
v We work in this sequential manner, requesting one page at  
a time, and have to wait for the server to respond, loading  
a whole new web page before we continue.  
v This is also one of the limitations of web pages, where  
transmitting information between a client and server  
generally requires a new page to be loaded.  
v JavaScript is one way to cut down on (some of) the client-  
server response time, by using it to verify form (or other)  
information before it’s submitted to a server.  
The usual way we operate in the Web  
v One of the limitations of JavaScript is (or used to  
be) that there was no way to communicate  
directly with a web server.  
v Another drawback to this usual sequential access  
method is that there are many situations where  
you load a new page that shares lots of the same  
parts as the old (consider the case where you have  
a “menu bar” on the top or side of the page that  
doesn’t change from page to page).  
Things change…  
v Until recently, we didn’t have any alternative to this  
load/wait/respond method of web browsing.  
v Ajax (sometimes written AJAX) is a means of using JavaScript to  
communicate with a web server without submitting a form or  
loading a new page.  
v Ajax makes use of a built-in object, XMLHttpRequest, to perform  
this function.  
v This object is not yet part of the DOM (Document Object Model)  
standard, but is supported (in different fashions) by Firefox,  
Internet Explorer, Safari, Opera, and other popular browsers.  
v The term “Ajax” was coined in 2005, but the XMLHttpRequest  
object was first supported by Internet Explorer several years  
before this.  
Ajax  
v Ajax stands for “Asynchronous JavaScript and XML”.  
v The word “asynchronous” means that the user isn’t  
left waiting for the server the respond to a request,  
but can continue using the web page.  
v The typical method for using Ajax is the following:  
§ 1) A JavaScript creates an XMLHttpRequest object,  
initializes it with relevant information as necessary, and  
sends it to the server. The script (or web page) can  
continue after sending it to the server.  
§ 2) The server responds by sending the contents of a file or  
the output of a server side program (written, for example,  
in PHP).  
§ 3) When the response arrives from the server, a JavaScript  
function is triggered to act on the data supplied by the  
server.  
§ 4) This JavaScript response function typically refreshes the  
display using the DOM, avoiding the requirement to reload  
or refresh the entire page.  
The Back End  
v The part of the Ajax application that resides on the web  
server is referred to as the “back end.  
v This back end could be simply a file that the server passes  
back to the client, which is then displayed for the user.  
v Alternatively, the back end could be a program, written in  
PHP, Perl, Ruby, Python, C, or some other language that  
performs an operation and sends results back to the client  
browser.  
v An XMLHttpRequest object can send information using the  
GET and POST methods to the server in the same way that  
an HTML form sends information.  
v Recall from our previous discussions that the GET request  
encodes the information inside of the URL, while a POST  
request sends its data separately (and can contain more  
information than a GET request can).  
Writing an Ajax application  
v We have to write the “front end” of the application in JavaScript to  
initiate the request.  
v The back end, as mentioned, processes the request and sends it’s  
response back to the client. The back end is typically a short program  
we write for performing some dedicated task. This could be scripted  
in any language that is capable of sending back communication to the  
browser, like PHP or Perl.  
v We also need to write the JavaScript response function for processing  
the response and displaying any results (or alterations to the web  
page).  
v The “x” in Ajax stands for XML, the extensible markup language. XML  
looks like HTML, which is no mistake as the latest versions of HTML are  
built upon XML. The back end could send data back in XML format and  
the JavaScript response function can process it using built-in functions  
for working with XML. The back end could also send plain text, HTML,  
or even data in the JavaScript format.  
The XMLHttpRequest object  
v The XMLHttpRequest object is the backbone of every Ajax  
method. Each application requires the creation of one of  
these objects. So how do we do it?  
v As with most things in web programming, this depends  
upon the web browser that the client is using because of  
the different ways in which the object has been  
implemented in the browsers.  
v Firefox, Safari, Opera, and some other browsers can create  
one of these objects simply using the “new” keyword.  
<script type="text/javascript">  
ajaxRequest = new XMLHttpRequest();  
</script>  
The XMLHttpRequest object (cont.)  
v Microsoft Internet Explorer implements this object using its  
proprietary ActiveX technology. This requires a different syntax  
for creating the object (and can also depend upon the particular  
version of Internet Explorer being used).  
v To handle different types of browsers, we use the  
try { . . . } catch (error) { . . . }  
v The “try” section attempts to execute some JavaScipt code. If  
an error occurs, the “catch” section is used to intervene before  
the error crashes the JavaScript (either to indicate an error has  
happened, or to attempt something else).  
v To create one of these objects we can use a sequence of try. . .  
catch blocks, attempting different ways to create an  
XMLHttpRequest object.  
The XMLHttpRequest object (cont.)  
function getXMLHttpRequest()  
/*  
This function attempts to get an Ajax request object by trying  
a few different methods for different browsers. */  
{
var request, err;  
try {  
request = new XMLHttpRequest();  
// Firefox, Safari, Opera, etc.  
}
catch(err) {  
try {  
// first attempt for Internet Explorer  
request = new ActiveXObject("MSXML2.XMLHttp.6.0");  
}
catch (err) {  
try {  
// second attempt for Internet Explorer  
request = new ActiveXObject("MSXML2.XMLHttp.3.0");  
}
catch (err) {  
request = false; // oops, can’t create one!  
}
}
}
return request;  
}
The XMLHttpRequest object (cont.)  
v As with any object in JavaScript (and other programming  
languages), the XMLHttpRequest object contains various  
properties and methods.  
v We list the most important of these properties and methods on  
the next slides.  
v The main idea is that the properties are set after the object is  
created to specify information to be sent to the server, as well  
as how to handle the response received from the server. Some  
properties will be updated to hold status information about  
whether the request finished successfully.  
v The methods are used to send the request to the server, and to  
monitor the progress of the request as it is executed (and to  
determine if it was completed successfully).  
XMLHttpRequest object properties  
Property  
Description  
v readyState  
An integer from 0. . .4. (0 means the call  
is uninitialized, 4 means that the call is  
complete)  
v onreadystatechange Determines the function called when the  
objects readyState changes.  
v responseText  
v responseXML  
Data returned from the server as a text  
string (read-only).  
Data returned from the server as an XML  
document object (read-only).  
v status  
v statusText  
HTTP status code returned by the server  
HTTP status phrase returned by the server  
We use the readyState to determine when the request has been  
completed, and then check the status to see if it executed without an  
error. (We’ll see how to do this shortly.)  
XMLHttpRequest object methods  
Method  
Description  
v open('method', 'URL', asyn)  
Specifies the HTTP method to be used (GET  
or POST as a string, the target URL, and  
whether or not the request should be  
handled asynchronously (asyn should be  
true or false, if omitted, true is  
assumed).  
v send(content)  
Sends the data for a POST request and  
starts the request, if GET is used you should call send(null).  
v setRequestHeader('x','y’) Sets a parameter and value pair x=y and  
assigns it to the header to be sent with the request.  
v getAllResponseHeaders()  
v getResponseHeader(x)  
v abort()  
Returns all headers as a string.  
Returns header x as a string.  
Stops the current operation.  
The open object method is used to set up the request, and the send method starts  
the request by sending it to the server (with data for the server if the POST  
method is used).  
A general skeleton for an Ajax application  
<script type="text/javascript">  
// ***** include the getXMLHttpRequest function defined before  
var ajaxRequest = getXMLHttpRequest();  
if (ajaxRequest) { // if the object was created successfully  
ajaxRequest.onreadystatechange = ajaxResponse;  
ajaxRequest.open("GET", "search.php?query=Bob");  
ajaxRequest.send(null);  
}
function ajaxResponse() //This gets called when the readyState changes.  
{
if (ajaxRequest.readyState != 4) // check to see if we’re done  
{ return; }  
else {  
if (ajaxRequest.status == 200) // check to see if successful  
{ // process server data here. . . }  
else {  
alert("Request failed: " + ajaxRequest.statusText);  
}
}
}
</script>  
A first example  
v Here’s an example to illustrate the ideas we’ve mentioned (inspired by  
an example in the book Ajax in 10 Minutes by Phil Ballard).  
v The main idea is that we’re going to get the time on the server and  
display it to the screen (and provide a button for a user to update this  
time). The point I want to demonstrate here is how to use Ajax to do  
this update without updating/refreshing the entire webpage.  
v We use a (very) small PHP script to get the date from the server, and  
return it as a string as a response to the request. Here is the script:  
<?php  
echo date('H:i:s');  
?>  
v I saved this as the file “telltime.php.  
v The HTML file and JavaScript code follows.  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN”  
"http://www.w3.org/TR/xhtml11/DTD/xhtml1-strict.dtd">  
<head>  
<title>Ajax Demonstration</title>  
<style>  
body {  
background-color: #CCCCCC;  
text-align: center;  
}
.displaybox {  
margin: auto;  
width: 150px;  
background-color: #FFFFFF;  
border: 2px solid #000000;  
padding: 10px;  
font: 1.5em normal verdana, helvetica, arial, sans-serif;  
}
</style>  
<script type="text/javascript">  
var ajaxRequest;  
function getXMLHttpRequest()  
/*  
This function attempts to get an Ajax request object by try in  
a few different methods for different browsers. */  
{
}
// same code as before. . .  
function ajaxResponse() //This gets called when the readyState changes.  
{
if (ajaxRequest.readyState != 4) // check to see if we're done  
{ return; }  
else {  
if (ajaxRequest.status == 200) // check to see if successful  
{
document.getElementById("showtime").innerHTML =  
ajaxRequest.responseText; }  
else {  
alert("Request failed: " + ajaxRequest.statusText);  
}
}
}
function getServerTime()  
update.  
// The main JavaScript for calling the  
{
ajaxRequest = getXMLHttpRequest();  
if (!ajaxRequest) {  
document.getElementById("showtime").innerHTML = "Request  
error!";  
return;  
}
var myURL = "telltime.php";  
var myRand = parseInt(Math.random()*999999999999999);  
myURL = myURL + "?rand=" + myRand;  
ajaxRequest.onreadystatechange = ajaxResponse;  
ajaxRequest.open("GET", myURL);  
ajaxRequest.send(null);  
}
</script>  
</head>  
<body onload="getServerTime();">  
<h1>Ajax Demonstration</h1>  
<h2>Getting the server time without refreshing  
the page</h2>  
<form>  
<input type="button" value="Get Server Time"  
onclick="getServerTime();" />  
</form>  
<div id="showtime" class="displaybox"></div>  
</body>  
</html>  
view the output page  
The main functionality is handled by the getServerTime()  
function in setting up and sending the XMLHttpRequest  
object, and the ajaxResponse() function to display the time.  
What’s this business with the random numbers?  
v Web browsers use caches to store copies of the web page.  
Depending upon how they are set up, a browser could use  
data from its cache instead of making a request to the web  
server.  
v The whole point of Ajax is to make server requests and not  
to read data from the cache. To avoid this potential  
problem, we can add a parameter with a random string to  
the URL so that the browser won’t be reading data from its  
cache to satisfy the request (as then it looks like a different  
request than previous ones).  
v This is only necessary if the request method is GET, as  
POST requests don’t use the cache. (This also seems to be  
more of an issue with Microsoft Internet Explorer than  
with other browsers.)  
Tải về để xem bản đầy đủ
pdf 37 trang Thùy Anh 27/04/2022 9280
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng Web technologies and e-Services - Bài 10: AJAX - Trường Đại học Bách khoa Hà Nội", để tải tài liệu gốc về máy hãy click vào nút Download ở trên

File đính kèm:

  • pdfbai_giang_web_technologies_and_e_services_bai_10_ajax_truong.pdf