【问题标题】:Loading XHR response data to index HTML page加载 XHR 响应数据以索引 HTML 页面
【发布时间】: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 响应?

【问题讨论】:

标签: javascript html asp.net-web-api ecmascript-6 xmlhttprequest


【解决方案1】:

这是一个例子:

var url = "https://sourceforge.net/projects/kaais/files/stats/json?start_date=2013-08-18&end_date=2018-04-19";

var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
  if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
    document.getElementById('output').innerHTML = JSON.parse(xmlHttp.responseText).total;
}
xmlHttp.open("GET", url, true);
xmlHttp.send();

HTML:

<div id="container">
  <div id="output">NO DATA</div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 2019-08-22
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多