XMLHttpRequest allows JavaScript to make HTTP requests, and is the most basic part of AJAX. It allows a website to dynamically request more content, without reloading the entire page.
OverviewThe XMLHttpRequest property is available on the window object.
var xhr = new XMLHttpRequest();
With the XMLHttpRequest object, clients can make HTTP requests to a URL without reloading the entire page. Despite the term “XML” in the name, this object can be used to retrieve any type of data.
PropertiesThe following script demonstrates how to create and use the XMLHttpRequest object. For best client-side performance, the request is asynchronous and uses an onreadystatechange event handler to process the data returned by the call.
function handler() {
if (xhr.readyState === 4 ) {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
}
}
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost/test.xml", true);
xhr.onreadystatechange = handler;
xhr.send();
This script demonstrates how to access resources that sits on a different domain. Example: siteA.com gets resource from siteB.com
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function getTitle(text) {
return text.match('<title>(.*)?</title>')[1];
}
function makeCorsRequest() {
var url = 'http://updates.html5rocks.com';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
xhr.onload = function() {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
Usage
The XMLHttpRequest object can be used to make either same-origin or cross-origin requests.
Same-origin requests are subject to the browser’s same-origin policy: http://en.wikipedia.org/wiki/Same_origin_policy This basically says that an XMLHttpRequest instance can make a request to a resource that lives on the same origin as the calling page.
Requests that go across origins (for example, a request from originA.com to originB.com) can also be made. But in order for them to work, the destination server must support Cross-Origin Resource Sharing (CORS, http://www.w3.org/TR/cors/). These are a set of headers included in the response that indicate how a resource can be accessed across domains.
Related specificationsXMLHttpRequest
Microsoft Developer Network: Windows Internet Explorer API reference Article
Portions of this content come from HTML5Rocks! article
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4