我怎样才能只抓取所选加密货币的价格值

时间:2021-05-14 02:28:00

标签: javascript html json api binance

目标:仅获取所选加密货币的价格!使用 Binance Public API

问题:返回整个 JSON 字符串,而不仅仅是所选货币的价格。

代码

  var burl = 'https://api.binance.com/api/v3/ticker/price?symbol='
  var symbol = 'BTCUSDT'
  var url = burl + symbol
  var ourRequest = new XMLHttpRequest()

  ourRequest.open('GET', url, true)
  ourRequest.onload = function() {
    console.log(ourRequest.responseText)
  }
  ourRequest.send()

现在公平一点,我知道我可以使用 .replace().split() + .join() 来只获取价格,但我相信有比使用该方法更简单的方法。

var burl = 'https://api.binance.com/api/v3/ticker/price?symbol='
var symbol = 'BTCUSDT'
var url = burl + symbol
var ourRequest = new XMLHttpRequest()

ourRequest.open('GET', url, true)
ourRequest.onload = function() {
  var str = ourRequest.responseText
  str = str.split('{"symbol":"BTCUSDT","price":"').join('')
  str = str.split('"}').join('')
  document.body.innerHTML = str
}
ourRequest.send()

我的问题是,我怎样才能仅以文本形式获取所选加密货币的价格值?

2 个答案:

答案 0 :(得分:2)

我觉得你可以这样做

  var burl = 'https://api.binance.com/api/v3/ticker/price?symbol='
    var symbol = 'BTCUSDT'
    var url = burl + symbol
    var ourRequest = new XMLHttpRequest()
    
    ourRequest.open('GET', url, true)
    ourRequest.onload = function() {
      var str = ourRequest.responseText
      var strobj = JSON.parse(str)
     document.body.innerHTML = strobj.price
    
    }
    ourRequest.send()

答案 1 :(得分:1)

与@EtsukoSusui 相同,但使用 fetch

const burl = 'https://api.binance.com/api/v3/ticker/price?symbol='
const symbol = 'BTCUSDT'
const url = burl + symbol
const res = await fetch(url)
const { price } = await res.json()
document.body.innerHTML = price