![](/img/trans.png)
[英]Display results of an API request on HTML page using JavaScript
[英]Display API request results in HTML page using only js
我对 js 和 API 有点陌生,
我写了一个小代码,假设去向 2 个网站询问一些数据,然后我只取一部分结果并将其添加到我的 html 页面。
我试图让它在第一个网站上工作,因为当我拥有第一个网站时,很容易让它在第二个网站上工作。
我只想使用 js 而不是 php 或其他语言。
它暂时不起作用......
所以这是我的 js
好吧,如果你现在才来,
我的代码已使用 Justin 和 Aashah 的以下 2 个答案进行了更新,现在的问题是浏览器说为了使用 cors 获取,我需要一个 http 或 https,并说 [object%20Object 存在问题],所以仍然没有数据显示,如果有人有解决方案,请帮助我们:)
var urlbitfinex = "https://api.bitfinex.com/v1";
var urlkraken = "https://api.kraken.com/0/public/Ticker?pair=";
var resultBitfinex;
//request bitfinex price
request.get(urlbitfinex + "/pubticker/btcusd",
resultBitfinex = function(error, response, body) {
console.log(body)
return body;
});
//request kraken price
request.get(urlkraken + "xbteur",
function(error, response, body) {
console.log(body);
});
//Pushing the result to the html
var price_USD = document.getElementById('price-usd');
var USDPrice = '<p>USDEUR Price:' + resultBitfinex.ask '</p>';
price_USD.innerHTML += USDPrice;
还有我的 html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="price-usd">
</div>
<script src="getPrices.js"></script>
</body>
</html>
您必须在回调中处理 UI 更改:
fetch({ url: urlkraken + "/pubticker/btcusd", cors: true })
.then(res => res.json())
.then(res => {
const price_USD = document.querySelector('#price-usd');
const USDPrice = '<p>USDEUR Price:' + res.ask + '</p>';
price_USD.innerHTML += USDPrice;
})
.catch(err => console.log(err));
你并没有真正对响应做任何事情。
如果您不必支持 IE,则可以使用fetch
。 这是一个取自的示例: 如何获取 XMLHttpRequest 的响应?
var url = "https://stackoverflow.com"; // Change this to your URL
fetch(url)
.then(function(response) {
if(response.ok) { // Check if response went through
response.json().then(function(data) {
var price_USD = document.getElementById('price-usd');
var USDPrice = '<p>USDEUR Price:' + data.something + '</p>';
price_USD.innerHTML += USDPrice;
});
} else { // Response wasn't ok. Check dev tools
console.log("response failed?");
}
});
更多关于Fetch
在这里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.