简体   繁体   English

试图在 HTML 中显示 API 数据

[英]Trying to Display API Data in HTML

I am trying to make an API call and display that data on my HTML page.我正在尝试进行 API 调用并在我的 HTML 页面上显示该数据。 Currently no data is displayed when the button is clicked, but the API call is made successfully as I can track my usage on another page.当前单击按钮时未显示任何数据,但 API 调用成功,因为我可以在另一个页面上跟踪我的使用情况。 My code is below:我的代码如下:

<!DOCTYPE html>
<html>
<body>

<h1>API Data</h1>

<div id="container">
    <div id="api">Nothing Yet</div>
</div>

<br>

<button type="button" onclick="loadAPI()">Change Content</button>

<script>
function loadAPI() {
  var xhttp = new XMLHttpRequest();
  xhttp.open("GET", "API URL with Token here", false);
  xhttp.addEventListener("load", loadData);
  xhttp.send();
}

function loadData() {
  document.getElementById('api').innerText = JSON.parse(this.responseText);
}
</script>

</body>
</html>

No data is displayed because you're not putting the data into the target element.没有数据显示,因为您没有将数据放入目标元素。

To insert data into #api, you need to do something like要将数据插入#api,您需要执行以下操作

document.getElementById('api').innerHTML = apiResponse; // no underscore
// or
document.getElementById('api').innerText = apiResponse;

I'll leave it for you to read up on security.我会把它留给你阅读安全性。 https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

Also, XMLHttpRequest is asynchronous unless specified otherwise (in a param).此外, 除非另有说明(在参数中),否则 XMLHttpRequest 是异步的。 So the most reliable way is to display the data in the load event listener.所以最可靠的方式是在load事件监听器中显示数据。 Your final code should be something like:您的最终代码应类似于:

// Making a XMLHttpRequest
function loadAPI() {
  var xhttp = new XMLHttpRequest();
  xhttp.open("GET", "API URL with Token Here", false);
  xhttp.addEventListener("load", loadData);
  xhttp.send();
}

// Displaying the data
function loadData() {
  document.getElementById('api').innerText = this.responseText;
}

Note if your response is in JSON, you need to JSON.parse(this.responseText) to access the array/objects.请注意,如果您的响应在 JSON 中,则需要JSON.parse(this.responseText)来访问数组/对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM