根据美元汇率以以太坊显示价格

  • 本文关键字:显示 美元 汇率 ethereum
  • 更新时间 :
  • 英文 :


WorldCoinIndex在此处发布其汇率:https://www.worldcoinindex.com/apiservice/json?key=eetjflffsrh1ffzrh1ffdm1flh1ffdm1xvlyksh1j5khk

如果商品为$ 300美元,我该怎么做以下?1)从此URL的数组中提取ETH/USD汇率2)定义价格,然后除以汇率3)在HTML页面中显示ETH价格?

您的问题实际上与以太坊无关,而是一个一般的Web开发问题。另外,我们不知道您的网站是建立在哪种平台上或您使用的编程语言。话虽这么说,这是一个功能齐全的节点。JS示例,您可以在本地尝试,该示例在单击按钮后可以更新页面上的价格。然后,您应该能够使其适应您的特定语言。

首先,您需要从nodejs.org安装node.js,创建一个新文件夹,然后在此文件夹中创建两个文件,app.js and Index.html。

app.js文件:

//install these two by running 'npm install request' and 'npm install express'
//from the command line in the newly created folder
const request = require('request');
const express = require('express');
//starting a local web server you can access at http://localhost:8547/
//and view the actual web page
var app = express(); 
app.listen(8547);
//make sure you get another apiKey if you go over the 70 requests/hour limit
const apiUrl = 'https://www.worldcoinindex.com/apiservice/json?key='
const apiKey = 'eEtjflfzZRH1fFdM1xVLykSH1j5khk';
//eth-usd pair is at the index 344 in the response JSON file
const ethIndexInJson = '344';
const requestUrl = apiUrl + apiKey;
//this is the response we'll send when user clicks the update price button
app.get('/eth-price', (req, res) => {
      request.get(requestUrl, (error, response, body) => {
      //here's the JSON response from worldcoinindex
      var json = JSON.parse(body);
      //and here's the actual price extracted
      priceOfEthInUsd = json.Markets[ethIndexInJson].Price_usd;
      //now we send back the price converted to a string 
      res.send(priceOfEthInUsd.toString());
    })            
})
//setting index.html as the home page
app.get('/', (req, res) => {        
    res.sendFile(__dirname + '/index.html');
})

这是您的index.html文件,它将随着新的ETH价格更新。它包含一个带有" enth-price",一个按钮和脚本的ID的段落,该段落将从app.js文件中请求新价格。您现在不应该太在乎整个XMLHTTP Mumbo-Jumbo。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <p id="eth-price">here's where the price will go</p>
    <button onclick="updatePrice()">Update price</button>
    <script>
    function updatePrice() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          //this is where we update the HTML with our new price contained
          //in the response
          var newPrice = this.responseText;
          document.getElementById("eth-price").innerHTML = newPrice;
        }
      };
      //eth-price is the path we defined in the app.js file in the get method
      xhttp.open("GET", "eth-price", true);
      xhttp.send();
    }
    </script>
  </body>
</html>

打开浏览器,前往http://localhost:8547,然后尝试。

最新更新