32
loading...
This website collects cookies to deliver better user experience
XMLHttpRequest
(aka XHR
) objectopen()
method of the XHR
to specify what kind of data you wantsend()
method to send the requestindex.js
file located in the root directory.var http = require("http");
var fs = require("fs");
function render(path, contentType, fn) {
fs.readFile(__dirname + "/" + path, "utf-8", function (err, str) {
fn(err, str, contentType);
});
}
//create a server object:
http
.createServer(function (req, res) {
var httpHandler = function (err, str, contentType) {
if (err) {
console.log(err);
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("An error has occured: " + err.message);
} else {
res.writeHead(200, { "Content-Type": contentType });
res.end(str);
}
};
if (req.url.indexOf("/scripts/") >= 0) {
console.log("Serving ajax.js");
render(req.url.slice(1), "application/javascript", httpHandler);
} else if (
req.headers["x-requested-with"] === "XMLHttpRequest" &&
req.headers["x-vanillaajaxwithoutjquery-version"] === "1.0"
) {
console.log("Processing AJAX request");
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Hello World!" }));
} else {
console.log("Serving index.html");
render("views/index.html", "text/html", httpHandler);
}
})
.listen(8080); //the server object listens on port 8080
http
module to create an HTTP server. For those of you that are not familiar with Node.js, here is a brief explanation of the code.8080
. The callback function we pass to the createServer()
method is executed for each request that comes in. Whenever a new request is received, the request
event is called, providing two objects: a request (an http.IncomingMessage
object) and a response (an http.ServerResponse
object). The request
provides the request details through which we can access the request headers
and request data
. The response
is used to populate the data returning to the client.var http = require("http");
//create a server object:
http
.createServer(function (req, res) {
// callback to handle request is define here
})
.listen(8080); //the server object listens on port 8080
if (req.url.indexOf("/scripts/") >= 0) {
render(req.url.slice(1), "application/javascript", httpHandler);
} else if (
req.headers["x-requested-with"] === "XMLHttpRequest" &&
req.headers["x-vanillaajaxwithoutjquery-version"] === "1.0"
) {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Hello World!" }));
} else {
render("views/index.html", "text/html", httpHandler);
}
scripts
directory, then the appropriate file is served with the application/javascript
content type. x-request-with
headers set to XMLHttpRequest
indicates an AJAX request. In this case, we simply return a "Hello World!" text message.index.html
file is served.render()
and httpHandler()
functions yet, so let's do that now. The render()
function asynchronously reads the contents of the requested file. It accepts the httpHandler()
callback function, which is used to check for errors and write the content of the file to the response with the appropriate HTTP status code if everything looks good.function render(path, contentType, fn) {
fs.readFile(__dirname + "/" + path, "utf-8", function (err, str) {
fn(err, str, contentType);
});
}
var httpHandler = function (err, str, contentType) {
if (err) {
console.log(err);
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("An error has occured: " + err.message);
} else {
res.writeHead(200, { "Content-Type": contentType });
res.end(str);
}
};
/views/index.html
file and the /scripts/ajax.js
script used for the button event handling. The index.html
is straightforward. It references the ajax.js
script which is called when the user clicks the Retrieve button.<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Vanilla Ajax without jQuery</title>
</head>
<body>
<h1>Vanilla Ajax without jQuery</h1>
<button id="retrieve" data-url="/">Retrieve</button>
<p id="results"></p>
<script src="/scripts/ajax.js" async></script>
</body>
</html>
ajax.js
script is where most of the AJAX magic happens.(function () {
var retrieve = document.getElementById("retrieve"),
results = document.getElementById("results"),
toReadyStateDescription = function (state) {
switch (state) {
case 0:
return "UNSENT";
case 1:
return "OPENED";
case 2:
return "HEADERS_RECEIVED";
case 3:
return "LOADING";
case 4:
return "DONE";
default:
return "";
}
};
retrieve.addEventListener("click", function (e) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
console.log(
"Inside the onreadystatechange event with readyState: " +
toReadyStateDescription(xhr.readyState)
);
if (xhr.readyState === 4 && xhr.status === 200) {
if (xhr.responseType === "json") {
results.innerHTML = xhr.response.message;
} else {
results.innerHTML = JSON.parse(xhr.responseText).message;
}
}
};
xhr.open("GET", e.target.dataset.url, true);
xhr.responseType = "json";
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("x-vanillaAjaxWithoutjQuery-version", "1.0");
xhr.send();
});
})();
Create an xhr
instance of the XMLHttpRequest
object using the XMLHttpRequest() constructor.
Use the open()
method of the XMLHttpRequest
object to specify the kind of data being requested. It takes three arguments:
Create a callback function to process the response. XHR
has two properties used to indicate a response from the server:
Finally, all we're left to do is send the request. But before we do that, we need to make sure we set the _ request headers _ accordingly to indicate that our request is indeed an AJAX request.
npm run start
, the server returns the rendered index.html
page to the browser. Since the index.html
file references the ajax.js
script, the browser issues another request to the server to get this file. Finally, when the user clicks the Retrieve button, the server returns the "Hello World!" message. This workflow can be observed via the server's terminal logger as shown below.Serving index.html
Serving ajax.js
Processing AJAX request