【发布时间】:2021-04-17 02:46:18
【问题描述】:
我有一个 .NET api 端点,它返回匿名数据,客户端通过 Promise 接收这些数据,如下所示:
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,
});
};
});
}
或通过这样的回调:
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);
};
或通过异步/等待
async function getDataByAsyncAwait() {
try {
console.log("By Async Await");
await getDataByPromise(method, url);
} catch (error) {
console.log(error);
}
}
或通过像这样的普通 XHR:
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();
}
如何通过按下按钮或将这些 JSON 对象显示在 html 文件中? 我应该将函数加载到这样的按钮中吗?
<button onclick="">Get Data By Normal XHR</button>
如果是这种情况,那么我应该将 XHR 请求的响应保存到数组或某种常量或变量中并显示它们吗? 或者我应该采取任何其他方法在 HTML dom 上显示 XHR 响应?
【问题讨论】:
-
感谢您的回复,但是他们在做 jquery 而我不是,所以我认为答案不适用于我的情况。
标签: javascript html asp.net-web-api ecmascript-6 xmlhttprequest