Java Reference
In-Depth Information
request("https://s3.amazo
↵
naws.com/sitepoint-book-content/jsninja/hello.htm") },
false);
api.addEventListener("click", function(){
request("http://ip.jsonte
↵
st.com/") }, false);
This calls the
request()
function when the button is clicked. This function is where the
Ajax request will happen. It accepts a URL as a parameter, which is where the request is
sent. Let's add this function to the end of the file:
scripts.js
(excerpt)
function request(url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("output").innerHTML = xhr.
↵
responseText;
}
}
xhr.open("GET", url, true);
xhr.send();
document.getElementById("output").innerHTML = "Waiting
for
↵
response ...";
}
Inside this function, we create a new
XMLHttpRequest
object and then assign an
anonymous function to the
onreadystatchange
property. This checks the
readyState
property to see if the request is complete (when the
readyState
property
is
4
). Once complete it replaces the inner HTML of the output div with the response text.
The
open()
method sets up an asynchronous GET request to the URL provided (depend-
ing on which button was pressed) and then the request is sent. Last of all, we update the
output div with a message saying
“Waiting for response ...”
. This demon-
strates the asynchronous nature of an Ajax request because it will be shown
before
the re-
sponse. The text and HTML files take very little time to be shown after they're downloaded
