我想抓取https://api.coindesk.com/v1/bpi/currentprice/BTC.json/
并收取比特币的价格,将其保存到变量中。到目前为止,这是我的js / jQuery代码
$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('https://api.coindesk.com/v1/bpi/currentprice/BTC.json/') + '&callback=?', function(data){
console.log(data.contents);
var za = $((data.contents).find("rate_float").text();
alert(za)
}));
我一直收到错误:
参数列表后面的Uncaught SyntaxError:missing) 它指向一行:
var za = $((data.contents).find("rate_float").text();
不知道出了什么问题。我一遍又一遍地检查过但是所有的括号都关闭了。任何帮助赞赏。感谢
答案 0 :(得分:1)
返回的值是JSON字符串。您需要解析才能将该字符串转换为js对象,如:
{
"time": {
"updated": "Mar 28, 2018 16:58:00 UTC",
"updatedISO": "2018-03-28T16:58:00+00:00",
"updateduk": "Mar 28, 2018 at 17:58 BST"
},
"disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
"bpi": {
"USD": {
"code": "USD",
"rate": "7,882.7938",
"description": "United States Dollar",
"rate_float": 7882.7938
},
"BTC": {
"code": "BTC",
"rate": "1.0000",
"description": "Bitcoin",
"rate_float": 1
}
}
}
为了获得USD rate_float,你可以写:
var za = JSON.parse(data.contents).bpi.USD.rate_float;
完整代码:
$.getJSON('http://www.whateverorigin.org/get?url=' +
encodeURIComponent('https://api.coindesk.com/v1/bpi/currentprice/BTC.json') + '&callback=?', function (data) {
console.log(data.contents);
var za = JSON.parse(data.contents).bpi.USD.rate_float;
alert(za)
});
答案 1 :(得分:1)
工作演示
// handles the click event, sends the query
function getSuccessOutput() {
$.ajax({
url:'https://api.coindesk.com/v1/bpi/currentprice/BTC.json',
complete: function (response) {
$('#output').html(JSON.parse(response.responseText).bpi.USD.rate_float);
},
error: function () {
$('#output').html('there was an error!');
},
});
return false;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onclick="return getSuccessOutput();"> Get USD price </a>
<hr>
<div id="output">Click on link to get the output</div>
&#13;