AJAX Model• Based on JavaScript running in browser – JavaScript code sends data to server, reads response – Response is simple data instead of entire page – Modifies page without re-ren
Trang 1CSCI 6962:
Server-side Design and Programming
Introduction to AJAX
Trang 2Client/Server Model
• Response is entire web page
• Very inefficient
– High network costs
– Must be loaded into browser and rendered
Trang 3AJAX Model
• Based on JavaScript running in browser
– JavaScript code sends data to server, reads
response
– Response is simple data instead of entire page – Modifies page without re-rendering it completely – AJAX: Asynchronous JavaScript and XML
Trang 4– Allows access to status of request
– Acts as reference to data sent back from
server as response
Server
JavaScript in Browser
XMLHttpRequest
Trang 5XMLHttpRequest Object
• XMLHttpRequest object represented
differently on different browsers
– Microsoft browsers represent as ActiveX
– Other browsers support directly
• Must use “browser safe” JavaScript to
create
– Provide method to check capabilities and return
object
– Place declaration of XMLHttpRequest object
directly in JavaScript so object created
automatically
Trang 6XMLHttpRequest Object
Will use this object in code
Trang 7• “Greeting” example
– Reads name from text element
– Sends to getGreeting servlet
Hello John!
Trang 8JavaScript Page Structure
Button contains onClick() call to JavaScript greet() function
Trang 9Opening Link to Server
• Syntax:
request.open(method, URL, asynchronous);
• Syntax if server requires name and password:
request.open(method, URL, asynchronous,
The URL of the server, including the servlet name and any parameters
Trang 10Adding Parameters to URL
• Data passed to server in form of request
http://domain/servletname?name=value&name=value&…
• Extract information from form (using
JavaScript/DOM)
• Append to URL to pass to server
• Open that URL
form.username.value
Trang 11Adding Parameters to URL
Form name = “form”
Field name = “username”
Extract the value of the username field of the form form
Append to request in
name=value format
Trang 12Sending Request/Receiving Response
• Send request to server:
requestObject.send();
• Get response back from server as string:
result = requestObject.responseText;
• Note: These commands must be in JavaScript
try/catch block in case no access to server
Trang 13Manipulating Page
• Use response to then manipulate page using
JavaScript/ Document Object Model
– Form element values
– Document properties
– Inserting new content…
Trang 14Creating Content at the Server
• Create servlet to handle request
– Gets data from request as before
• Writes result to response object
– Create printWriter to response object using getWriter() – Write string to printWriter using print(String) method
Trang 15Asynchronous Access
• Getting response from server may take time
– Slow network access, lengthy response …
• Can continue with other tasks while waiting for
response
– Spawn separate asynchronous process to handle
response when it arrives
Get information from form
Open request to server
Send request
Continue other tasks
(user interface, animation,etc.)
Wait for response When response received, handle it (possibly
changing page
Trang 16Continue other tasks
(user interface, animation,etc.)
function functionName() {
Wait for response When response received, handle it
}
Trang 17Asynchronous Access
Trang 18Status Checking
• Can track progress of response
– Keep user up to data on status
request.readystate
– Returns number indicating status of
request
1 (loading) Request object created, but send method not called
2 (loaded) send method called, but response not yet available
3 (interactive) Some data received, and responseText will give
current partial results
4 (completed) All data received
Trang 19Status Checking
Display message while waiting
Display response when loaded
Trang 20Validation servlet
Next page JSP
form data errors form submission next page
Trang 21• Client-side validation
– Form can call function when SUBMIT button
pressed
<form action = “nextPage”
onSubmit = return validateFunction()>
– If function returns false, form not submitted
function validateFunction() {
validate form data
if (form valid) return true;
else return false;
}
Trang 22• Validation outline using AJAX:
function validate() {
var ok = true; // Any errors yet?
for (all elements on form we must validate) {
append form data to URL
send request to validation servlet for that data response = request.responseText;
Trang 24If no errors, return empty string
Do validation checks and create appropriate error message
Send message
back to client
Trang 25Get quantity from form and submit to servlet
If no error message returned, return true (allows form submit)
Otherwise, display error message and return false
(prevents form submit)
Trang 27Timer Events
• Servlet creates illusion of “real-time” data
– Get input from sensors, etc at regular intervals – Based on data submitted asynchronously by other
users (online gaming, etc.)
AJAX in
browser
Server
Servlet
Game database
request data about state of game
form submission
moves change game state database game state
Other players
Other players
Trang 28Timer Events
• Simple example:
Server returns random number every time called by a client
Trang 29Timer Events
• Create timer object in JavaScript
• Attach timer to JavaScript function:
Interval in miliseconds
Trang 31Timer Events
• Call to server best if asynchronous
– Call to server may take longer than interval
– Potential problems if JavaScript tries to call
function again before previous call done
– Asynchronous form avoids by creating separate
process each time
Trang 32Timer Events
• Update page when response returned from
server