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

时间:2017-12-13 17:59:43

标签: ethereum

Worldcoinindex在此处公布其汇率:https://www.worldcoinindex.com/apiservice/json?key=eEtjflfzZRH1fFdM1xVLykSH1j5khk

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

1 个答案:

答案 0 :(得分:0)

您的问题实际上与以太坊无关,它更像是一般的网络开发问题。此外,我们不知道您的网站是基于什么平台或您使用的编程语言。话虽这么说,这是一个功能齐全的node.js示例,您可以在本地尝试在单击按钮后更新页面上的价格。然后,您应该能够根据您的特定语言进行调整。

首先,您需要从nodejs.org安装node.js,创建一个新文件夹并在此文件夹app.js和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价格进行更新。它包含一个id为'eth-price'的段落,一个按钮和一个脚本,它将从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并尝试一下。