【问题标题】:How can I ONLY grab the price value of selected crypto currency我如何才能只获取所选加密货币的价格值
【发布时间】:2021-08-04 06:37:09
【问题描述】:

目标:只获取选定加密货币的价格价值!使用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()

我的问题是,我怎样才能只获取所选加密货币的价格值作为文本?

【问题讨论】:

    标签: javascript html json api binance


    【解决方案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
    

    【讨论】:

      【解决方案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()

      【讨论】:

      • ROFL 哇,我不敢相信我没有想到这一点
      猜你喜欢
      • 2020-10-02
      • 1970-01-01
      • 2022-11-12
      • 2021-04-08
      • 2021-08-02
      • 2022-01-15
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      相关资源
      最近更新 更多