将 API 请求转换为要在站点中使用的文本

Convert API request to text to use in site

本文关键字:文本 站点 请求 API 转换      更新时间:2023-09-26

我正在尝试发出API请求并将返回放在div中。我做错了什么?

<!DOCTYPE HTML>
<html>
<head>
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://data.mtgox.com/api/2/BTCUSD/money/ticker_fast?pretty", false);
xhr.send();
xhr = function() {
document.getElementById("myDiv").innerHTML=xhr.responseText;
}
</script>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
您需要

绑定到onload侦听器,而不是将值设置为 xhr

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://data.mtgox.com/api/2/BTCUSD/money/ticker_fast?pretty", false);
xhr.onload = function() {
  document.getElementById("myDiv").innerHTML=this.responseText;
};
xhr.send();

请参阅 MDN 文档 关于使用 XMLHttpRequest。

你需要

xhr.onload = function() { //onload
   document.getElementById("myDiv").innerHTML=xhr.responseText;
}