我如何才能只获取所选加密货币的价格值



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

现在公平地说,我知道我可以使用.replacement((或.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()

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

我认为你可以这样做

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()

与@EtsukoSuui相同,但使用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

最新更新