jQuery in Action

226
CHAPTER 8
Talk to the server with Ajax
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300) {
document.getElementById('someContainer')
.innerHTML = xhr.responseText;
}
}
}
xhr.open('GET','/serverResource');
xhr.send();
Although there's nothing tricky going on here, that's a non-trivial amount of
code; 19 lines or so--even accounting for blank lines that we added for readabil-
ity and one line that we artificially broke in two so that it would fit on the page.
The equivalent code we'd write as the body of a ready handler using jQuery is
as follows:
$('#someContainer').load('/serverResource');
We're betting that we know which code you'd rather write! Let's look at the
jQuery command that we used in this statement.
8.2.1 Loading content with jQuery
The simple jQuery statement from the previous section easily loads content from
the server-side resource using one of the most basic, but useful, jQuery Ajax com-
mands:
load()
. The full syntax description of this command is as follows:


Listing 8.3
Using native XHR to include an HTML fragment


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.