仅使用js在HTML页面中显示API请求结果 [英] Display API request results in HTML page using only js

查看:131
本文介绍了仅使用js在HTML页面中显示API请求结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对js和API有点陌生,

I'm kinda new to js and API,

我写了一些代码,想去问两个网站一些数据,然后我只取一部分结果并将其添加到我的html页面中.

I have written a little code that is suppose to go ask 2 websites some data, then I only take a part of the result and add it to my html page.

我正在尝试使其与第一个网站一起使用,因为当我拥有第一个网站时,很容易使其在第二个网站上工作.

I'm trying to get it work with the first website as it will be easy to make it work on the second one when I'll have the first.

我只想使用js,而不要使用php或其他语言.

I want to use only js and not php or other languages.

暂时不起作用...

这是我的js

好吧,如果你现在才来的话,

Ok if you come here only now,

我的代码已使用下面的贾斯汀(Justin)和Aashah(Aashah)的以下2个答案进行了更新,现在的问题是浏览器说,要使用cors进行抓取,我需要使用http或https,并表示[object%20Object],因此仍然没有数据显示,如果有人有解决方案,请帮助我们:)

My code has been updated using the 2 answers below of Justin and Aashah, the issue now is that the browser says that in order to fetch with cors, I need a http or https, and says that there is an issue with [object%20Object], so still no data showing up, if someone has a solution, please help us :)

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>

推荐答案

您对响应实际上并没有做任何事情.

You aren't really doing anything with the response.

如果您不必支持IE,则可以使用 fetch .这是一个摘自的例子:如何获取XMLHttpRequest的响应?

If you don't have to support IE you can use fetch. Here's an example taken from: How to get the response of 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 的更多信息此处.

这篇关于仅使用js在HTML页面中显示API请求结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆