Title: Ajax (Asynchronous JavaScript and XML)
1Ajax(Asynchronous JavaScript and XML)
2AJAX
- Enable asynchronous communication between a web
client and a server. - A client is not blocked when an asynchronous
request is sent to a server. It assigns an event
handler to intercept the response instead. - The technology is not limited to XML encoded data.
3JavaScript Building a Request (4 steps)
- Step 1 Creating a XML HTTP Request object
- var xmlhttp new XMLHttpRequest()
- Step 2 Specifying where and how to retrieve the
resource - xmlhttp.open('GET', 'foo.jsp', true)
- Step 3 Setting a function to be called when the
response is returned by the server - xmlhttp.onreadystatechange function()
- // Code to handle the response here
-
- Step 4 Send the request
- xmlhttp.send(null)
- Note Between step 2 and 3, the order is not
important.
4Step 1 Creating a XML HTTP Request object
- Firefox, Opera, Safari, IE 7
- var xmlhttp new XMLHttpRequest()
- For earlier version if IE (lt 7)
- var xmlhttp new ActiveXObject(MSXML_ProgID)
- where MSXML_ProgID is a string identifying the
Microsoft XML Core Services (MSXML) installed on
the client machine. - It could be "Msxml2.XMLHTTP.4.0",
"Msxml2.XMLHTTP", - Note To avoid code branching, you may want to
use Sarissa (http//dev.abiss.gr/sarissa/). It is
an ECMAScript library acting as a cross-browser
wrapper for native XML APIs
5Step 2 Specifying what resource to retrieve
- var xmlhttp new XMLHttpRequest()
- xmlhttp.open(method, URL, isAsync)
- method Typically 'GET' or 'POST'
- URL Identify the resource we want to retrieve
- isAsync
- true ? Asynchronous transmission
- false or omitted ? Synchronous transmission
- Note This method call does not cause any
connection to establish.
6Step 2 Specifying what resource to retrieve
- The second parameter (URL) can be a relative path
or a complete URL. - By default, browsers only allow XML HTTP request
to be sent to the server where the current
document resides (for privacy and security
reasons). - So the complete URL must have the same domain as
the current document. - Method open() may also take an additional 4th and
5th parameters (userid and password). The two
parameters are used to bypass HTTP authentication.
7Step 3 Setting a call-back function
- xmlhttp.onreadystatechange function()
- // Code to handle the response here
-
- Each XMLHttpRequest object has a property named
readyState, which holds the status of the
server's response. - The event handler onreadystatechange is invoked
whenever the value of readyState changes.
8Step 3 Setting a call-back function
- Here are the possible values for the readyState
property
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete
- To only process the response when the request is
completed, one could write the call-back function
as - xmlhttp.onreadystatechange function()
- if (xmlhttp.readyState 4)
- // Code to handle the response here
-
-
9Step 4 Send the request
- xmlhttp.send(payload)
- Makes the connection to the URL specified in
open() - If request is asynchronous, this call returns
immediately. Otherwise this call blocks further
execution until the requested resource has been
fully downloaded. - If the request type is POST, payload (a string)
will be sent as the body of the request. If
nothing is to be sent or if request type is GET,
then pass null to the method
10Step 4 Send the request
- To make a POST request, we will also need to set
the "Content-type" header to let the server know
how to handle the content. - e.g., to emulate form submission, we can write
- xmlhttp.setRequestHeader(
- 'Content-type',
- 'application/x-www-form-urlencodedcharsetUTF-
8' - )
- xmlhttp.send('param1value1param2value2')
- setRequestHeader() could also be used to set
application-specific headers or override default
headers.
11Other XMLHttpRequest Methods
- abort()
- Cancel and stop the current request
- getResponseHeader("header")
- Returns the string value of a specified header in
the response (e.g. "Content-type") - Note The specified header is case-insensitive
- getAllResponseHeaders()
- Returns all headers from the response in a single
string - Useful for debugging or searching for a
particular string in the header
12XMLHttpRequest Properties
- status
- The HTTP status code from the server
- e.g., 200 for OK, 404 for Not Found, etc.
- statusText
- The text version of the status
- readyState
- The state of the request
- 0uninitialized, 1loading, 2loaded,
3interactive, and 4complete
13XMLHttpRequest Properties
- responseText
- Unparsed text of the response
- responseXML
- Response parsed into a DOM object happens only
if Content-type is text/xml. - onreadystatechange
- Event handler that is called when readyState
changes
14lthtmlgtltheadgt ltscript type"text/javascript"gt funct
ion changeDisplay() var fileTF
document.getElementById("filename") var
filename fileTF.value var request new
XMLHttpRequest() request.open("GET", filename,
true) request.onreadystatechange function()
if (request.readyState 4) var
area document.getElementById("display")
area.innerHTML request.responseText
request.send(null) lt/scriptgt lt/headgt ltbodygt ltf
orm name"myForm"gt File to load ltinput
id"filename" type"text" value"" /gt ltinput
type"button" value"Load" onclick"changeDisplay(
)" /gt lt/formgt ltdiv id"display"
style"backgroundcyan"/gt Ajax example
lt/divgt lt/bodygtlt/htmlgt
Example Load a file and display its content in a
DIV element.
15Cross-site XMLHttpRequest
- XMLHttpRequest object can only send request to
the same website. - To access web services or retrieve data from
other sites, you need to write a server side
script to serve as a proxy.
16References
- W3C Working Drawf The XMLHttpRequest Object
- http//www.w3.org/TR/XMLHttpRequest/
- Wiki XMLHttpRequest
- http//en.wikipedia.org/wiki/XMLHttpRequest