I have a .NET api endpoint that returns anonymous data and client side received these either through Promise like this:
function getDataByPromise(method, url) {
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.send();
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText,
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText,
});
};
});
}
or through Callback like this:
function getDataByCallback(method, url, done) {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.send();
xhr.onload = function () {
done(null, xhr.response);
};
xhr.onerror = function () {
done(xhr.response);
};
or through Async/Await
async function getDataByAsyncAwait() {
try {
console.log("By Async Await");
await getDataByPromise(method, url);
} catch (error) {
console.log(error);
}
}
or through normal XHR like this:
function getDataByXHR(method, url) {
let xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onload = function () {
console.log("By XHR: ");
console.log(xhr.response);
let gameSettings = JSON.parse(xhr.response);
this.data = gameSettings;
waitAsyncAwait(this.data);
waitPromise(this.data);
};
xhr.onerror = function () {
console.error("An error occur getting the XMLHttpRequest");
};
xhr.send();
}
How can I display these JSON object in the html file either by pushing a button or to a table? Should I load a function into a button like this?
<button onclick="">Get Data By Normal XHR</button>
If that is the case then should I save the response of the XHR request into an array or const or variable of some sort and display them? Or is there any other approach I should take to display the XHR response on the HTML dom?