xxxxxxxxxx
// 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();
// in modern times, we generally prefer `fetch`
// `fetch` will send a GET request by default
fetch("someurl")
.then(function(res) {
// if the request succeeded
if (res.status >= 200 && < 300) {
// a useful alternative is `res.json();`
return res.text();
} else {
// this will trigger the `catch` statement
throw new Error("Request failed.");
}
})
.then(function(data) {
console.log(data);
})
.catch(function(err) {
console.warn(err);
});
// we can also use the `await` keyword to handle fetch synchronously
const res = await fetch("someurl");
// ...
xxxxxxxxxx
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(this.readyState === 4 && this.status === 200)
{
document.getElementById('response-div').innerHTML = this.responseText
}
}
//get request with params
xhr.open('GET', 'example?param1=true¶m2=2');
xhr.send();
});
xxxxxxxxxx
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();
xxxxxxxxxx
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();
xxxxxxxxxx
// 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));