// create request
const request = new XMLHttpRequest();
// function to handle result of the request
request.addEventListener("load", function() {
// if the request succeeded
if (request.status >= 200 && request.status < 300) {
// print the response to the request
console.log(request.response);
}
});
// open the request
request.open("GET", "someurl");
// send the request
request.send();
// note: following are the shortest examples
// synchronous request, will block main thread
function requestSync(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.send();
return xhr.responseText;
};
console.log(requestSync("file.txt"));
// async
function requestAsync(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => resolve(xhr.response);
xhr.send();
});
}
requestAsync("file.txt").then((res) => console.log(res));
var url = "https://jsonplaceholder.typicode.com/posts";
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}
};
xhr.send();
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();