Tuesday, September 9, 2014

XMLHttpRequest (XHR)

XMLHttpRequest() is an object (a constructor function) that allows you to send HTTP requests from JavaScript.

AJAX stands for Asynchronous JavaScript and XML

two steps to using the XMLHttpRequest:

  • Send the request—this includes creating an XMLHttpRequest object and attaching an event listener
  • Process the response—your event listener gets notified that the response has arrived


Send the Request

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = myCallback;
xhr.open('GET', 'somefile.txt', true);
xhr.send('');

HTTP request GET, POST, HEAD
The last parameter is a boolean specifying whether the request is asynchronous (true) or not (false).

Process the Response

There is a property of the XHR object called readyState

Every time it changes, the readystatechange event fires

0—uninitialized
1—loading
2—loaded
3—interactive
4—complete (response is back)

function myCallback() {
if (xhr.readyState < 4) {
return; // not ready yet
}
if (xhr.status !== 200) {
alert('Error!'); // the HTTP status code is not OK
return;
}
// all is fine, do the work
alert(xhr.responseText);
}




No comments:

Post a Comment