HTML and CSS Reference
In-Depth Information
to load content dynamically. Asynchronous JavaScript and XML (Ajax) is a means
of loading and injecting content into a page without having to reload the entire page.
For instance, websites such as Twitter and Facebook use Ajax to add new posts to their
2 See .
Really simple Ajax
Ajax uses an object called XMLHttpRequest (XHR) to load content from a URL us-
ing JavaScript. This content then can be added to the page by using, for instance, the
innerHTML property of HTML elements.
At its very simplest, using Ajax might look like the following:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = responseReady;"GET","content.txt",true);
The var keyword creates a new variable, which is just like a property—it's a con-
tainer that holds some value that can be read or written to. The new variable in this case
holds a new XMLHttpRequest object instance (the new keyword creates this object).
A function is then set to handle the onreadystatechange event, which will be fired
when the XHR object has retrieved some content. The open() method then specifies
the kind of method used to retrieve the file, the filename, and whether the request is
asynchronous (the script continues while the external file loads) or synchronous (the
script waits for the external file to load before continuing). Setting this to true makes
it asynchronous and false sets it to synchronous. The event handling function might
look like this:
function responseReady() {
document.body.innerHTML = xmlhttp.responseText;
This script will set the content on the page to the content that was inside the loaded
text file.
As a complete example, we'll create a simple page with a next button and a previous
button and a message that loads between the two. Duplicate the jstemplate directory
Search WWH ::

Custom Search