<
script
type
=
"application/javascript;version=1.8"
>
function
refreshServerInfo
() {
const
req
=
new
XMLHttpRequest
();
req
.
addEventListener
(
'load'
,
function
() {
// TODO: put these values into HTML
console
.
log
(
this
.
responseText
);
});
req
.
open
(
'GET'
,
'http://localhost:7070'
,
true
);
req
.
send
();
}
refreshServerInfo
();
</
script
>
This script executes a basic Ajax call. We first create a new
XMLHttpRequest
object,
and then we add a listener that listens for the
load
event (which is what will get called
if the Ajax call was successful). For now, we just print the server response (which is in
this.responseText
) to the console. Then we call
open
, which is what actually estab‐
lishes the connection to the server. We specify that it’s an HTTP GET request, which
is the same method used when you visit a web page with your browser (there are also
POST and DELETE methods, among others), and we provide the URL to the server.
Finally, we call
send
, which actually executes the request. In this example, we’re not
explicitly sending any data to the server, but we could.
If you run this example, you’ll see the data that’s returned from the server show up on
the console. Our next step is inserting this data into our HTML. We structured our
HTML so that we could simply look for any element that has the data attribute
replace
, and replace that element’s contents with the data from the object that was
returned. To accomplish this, we iterate over the properties that were returned from
the server (using
Object.keys
), and if there are any elements with matching
replace
data attributes, we replace their contents:
req
.
addEventListener
(
'load'
,
function
() {
// this.responseText is a string containing JSON; we use
// JSON.parse to convert it to an object
const
data
=
JSON
.
parse
(
this
.
responseText
);
// In this example, we only want to replace text within the <div>
// that has class "serverInfo"
const
serverInfo
=
document
.
querySelector
(
'.serverInfo'
);
// Iterate over the keys in the object returned from the server
// ("platform", "nodeVersion", and "uptime"):
Object
.
keys
(
data
).
forEach
(
p
=>
{
// Find elements to replace for this property (if any)
const
replacements
=
serverInfo.querySelectorAll(
`[data-replace="
${
p
}
"]`
);
// replace all elements with the value returned from the server
for
(
let
r
of
replacements
) {
r
.
textContent
=
data
[
p
];
Ajax | 273