XMLHttpRequest
object
XMLHttpRequest
to make an asynchronous request to
datetime.php
function getDateTime() {
// Create the XMLHttpRequest
var xhr = new XMLHttpRequest();
// Create load event handler
xhr.addEventListener("load", responseReceived);
// Initialize an HTTP GET request
xhr.open("GET", "/~fmccown/datetime.php");
// Send the request asynchronously
xhr.send();
}
load
event handler is called when the response
is received (shown later in the notes)
open(requestMethod, URL)
- setup an http request
using the requestMethod
(GET or POST) to the given
URL
send(postString)
- make the http request passing the
postString
if using POST or nothing for GET
function responseReceived() {
// Put the text from Taz into the web page's span
if (this.status == 200) {
document.getElementById("datetime").innerHTML = this.responseText;
}
else {
document.getElementById("datetime").innerHTML = "Unable to obtain the date/time.";
}
}
responseReceived()
is called automatically when the http
response is received
this
- object that refers to the XMLHttpRequest object that
made the request
status
- http status code of the response (200, 404, etc.)
responseText
- entire response body
<input type="button" value="Get Date/Time on Web Server" onclick="getDateTime()">
<span id="datetime"></span>
datetime.php
,
but the server can respond with XML or JSON
{"year":"2017","month":"11","day":"27","hour":"14","minute":"50","second":"17"}
function getDateTime() {
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", responseReceived);
xhr.responseType = "json";
xhr.open("GET", "/~fmccown/datetimejson.php");
xhr.send();
}
function responseReceived() {
if (this.status === 200) {
// JSON converted into JavaScript object this.response
console.log("year = " + this.response.year);
console.log("time = " + this.response.hour + ":" + this.response.minute +
":" + this.response.second);
}
else {
console.log("Unable to contact datetimejson.php");
}
}
open()
are subject to the
same origin policy
meaning the URL must point to the same web server
from which the JavaScript code originated
// Error if JS is from http://www.harding.edu!
asyncRequest.open("GET", "http://otherwebsite.com/");