www.cisdocs.com

Download Report

Transcript www.cisdocs.com

JavaScript, Fifth Edition
Chapter 12
Updating Web Pages with AJAX
UNDERSTANDING HTTP
JavaScript, Fifth Edition
2
Understanding HTTP Messages
• HTTP transmission protocol consists of messages
– HTTP client requests and server responses
• HTTP client opens a connection to the server
– Submits a request message
• Web server returns a response message
appropriate to the request type
JavaScript, Fifth Edition
3
Understanding HTTP Messages
• All messages contain Headers
– Define information about the request or response
message and about the contents of the message
body
JavaScript, Fifth Edition
4
Sending HTTP Requests
• Most common types of HTTP requests
– GET and POST
• GET method
– Used for standard Web page requests
– Can have a query string or form data appended to the
URL
• POST request
– Similar to a GET request except that any submitted
data is included in the message body
JavaScript, Fifth Edition
5
Receiving HTTP Responses
• HTTP response messages
– Take the same format as request messages
• Status codes format
– 1xx: (informational) - Request received
– 2xx: (success) - Request successful
– 3xx: (redirection) - Request cannot be completed
without further action
– 4xx: (client error) - Request cannot be fulfilled due to
a client error
– 5xx: (server error) - Request cannot be fulfilled due to
a server error
JavaScript, Fifth Edition
6
Receiving HTTP Responses (cont’d.)
– Common response status codes
JavaScript, Fifth Edition
7
HOW AJAX WORKS
JavaScript, Fifth Edition
8
Introducing AJAX
• AJAX (Asynchronous JavaScript and XML)
– Collection of programming techniques that allow
browsers to retrieve data on demand from the Web
without having to load a new Web page or reload the
current page
– AJAX is not a programming language; it represents
the combination of several techniques (HTML,
JavaScript, XML, and HTTP asynchronous
communication) to create fully interactive Web
applications
• XML
– Format used for exchanging data
The Classic
Web Application Model
• Users interact with Web servers through a Web
page loaded on their browser
• Level of information is exchanged in pages: one
page to request information;
another page to
report on results of
the request
The Classic
Web Application Model
• Exchange of information is synchronous because
the user sends a request and must wait for a
response from the server before doing anything else
The AJAX
Web Application Model
• Adds an intermediary between user and server-side
system – an AJAX engine – that is responsible for
communicating with the server and returning
information from server to user interface
• User interface interacts with the AJAX engine using
code written in JavaScript, but the engine
communicates with the server using the same HTTP
request protocol that the classic model employs to
request/receive Web pages
The AJAX
Web Application Model
The AJAX
Web Application Model
• Communication is asynchronous; AJAX engine
handles server requests, leaving user free to interact
with the rest of the Web page
The AJAX
Web Application Model
• Asynchronous communication
– User does not have to wait for a response from the
server to do other tasks on the Web page
– Several AJAX engines can be employed
simultaneously to allow for exchange of data from
several different sources
– Because the server is generating only specific and
smaller chunks of information and not an entire Web
page, the load on the server is lessened
Introduction to AJAX (cont’d.)
Figure 12-1 Google Suggest list box
JavaScript, Fifth Edition
16
Introduction to AJAX (cont’d.)
Figure 12-3 HTTP request with the XMLHttpRequest object
JavaScript, Fifth Edition
17
Limitations of AJAX
• Requires JavaScript to be running on user’s browser
– If a user disables JavaScript on the browser for
security reasons, AJAX applications are disabled
• Does not record user’s browser history
– cannot use browser’s Back button to retrieve
information or bookmark information returned by
AJAX
• Can pose a problem for users with special needs
• If too many AJAX engines run simultaneously,
making calls to the Web server, communication with
the server may be compromised
IMPLEMENTING AJAX
JavaScript, Fifth Edition
19
Implementing Ajax
• AJAX engines are created using the
XMLHttpRequest object
– native JavaScript object that stores an HTTP request
to the server
– Key to turning JavaScript script into AJAX programs
– Allows use of JavaScript and HTTP to exchange data
between a Web browser and a Web server
– To create an XMLHttpRequest object:
– var myhttpRequest = new XMLHttpRequest();
Overview of Creating an AJAX Script
• Steps to create an AJAX script
– Instantiate an XMLHttpRequest object for the Web
browser where the script will run
– Use the XMLHttpRequest object to send a request
to the server
– Read and process the data returned from the server
JavaScript, Fifth Edition
21
Exploring the
XMLHttpRequest Object
• Methods associated with the XMLHttpRequest object
Used in every
AJAX application
Exploring the
XMLHttpRequest Object
• The open() method specifies the server resource to
access with the request object:
req.open(method, url, async, user, pwd)
– The method parameter has two possible values: GET
and POST
• The get method sends data to the Web server by
attaching a field name/value pair to the URL
• The post method sends data in a separate stream
from the URL (several advantages)
• The send() method sends data to the server:
req.send(content)
Request example
var myReq = new XMLHttpRequest();
myReq.open(“get”, “datafile.txt”, true);
myReq.send();
Note: true means it is an asynchronous
request
JavaScript, Fifth Edition
24
Exploring the
XMLHttpRequest Object
• Processing the XMLHttpRequest response
– The state of the response is constantly changing until the
response is complete:
– Stages of interaction between browser and server:
• Uninitialized: Request object is created
• Loading: Open() method is called
• Loaded: Browser successfully sends the request using the
send() method, but has received no response from the server
• Interactive: Browser begins receiving a partial response from
the server
• Complete: Server has completed sending a response to the
browser
Exploring the
XMLHttpRequest Object
• Properties of the request object
Exploring the
XMLHttpRequest Object
• The server will send two codes to the client –
– Ready State code (updated automatically)
– Status code
– Before processing the data from the response, must
confirm that the request was successfully handled by
the server by examining both codes
Exploring the
XMLHttpRequest Object
• To test when the server has responded to a request:
req.onreadystatechange =
function()
{
if (this.readyState == 4)
{
if (this.status = 200)
{
process the response
}
}
}
Receiving Server Data
• the type of data expected, dictates the response
property to evaluate
• responseXML property
– Contains the HTTP response as an XML document
• responseText property
– Contains the HTTP response as a text string
JavaScript, Fifth Edition
29
Parsing the response
• XML and HTML documents share same document object
model
– Create element and attribute nodes
– Navigate through the node tree – it’s complicated!
• To retrieve an XML document object:
var xmlDoc = req.responseXML
– To reference a collection of elements within the XML
document:
var elemArr = xmlDoc.getElementsByTagName(elem)
– To return text of an element in an XML document:
elemArr[i].firstChild.nodeValue
Ajax implementations
• Common uses of AJAX
–
–
–
–
Text Files
XML data
RSS syndications
Web services
RSS
• Really Simple Syndication (RSS) language
– One of the more important XML vocabularies
– Used to distribute news articles, or any content that
changes on a regular basis, to a group of subscribers
– Subscribers receive periodic updates using a feed
reader or an aggregator (e.g., iTunes)
– A podcast delivers audio or video content, but the
language that organizes and describes it is RSS
– RSS code follows conventions of all XML documents
Accessing Content on a Separate
Domain
• Web service, or XML Web service
– Software component residing on a Web server
– Does not contain graphical user interface or
command-line interface
– Simply provides services and data in the form of
methods and properties
• Up to the client to provide an implementation for a
program calling a Web service
JavaScript, Fifth Edition
33
Understanding AJAX’s Limitations
• Data requested must be located on the Web server
running the JavaScript program
• If data is on another domain
– use a server-side script as a proxy to access it
• proxy
– Someone or something that acts or performs a request
for another thing or person
JavaScript, Fifth Edition
34