从 JSON 创建表
2020-10-18
199
我正在尝试从 JSON 创建表格。我认为我的链接有问题,但其实没有问题。我的表格上没有显示任何数据。我的错误是:
Cannot read property 'symbol' of undefined 'Uncaught TypeError: Cannot read property 'symbol' of undefined at Object. (main.js:14) at Function.each (jquery.min.js:2) at Object.success (main.js:11) at u (jquery.min.js:2) at Object.fireWith [as resolveWith] (jquery.min.js:2) at k (jquery.min.js:2) at XMLHttpRequest.'
这是我的 JS 代码
$(document).ready(function() {
$.getJSON("https://api.coindesk.com/v1/bpi/currentprice.json", function(json) {
enter code here
var currentprice = '';
$.each(json.bpi, function(key, value) {
var USD = value.USD
currentprice += '<tr>';
currentprice += '<td>' + USD.symbol + '</td>';
currentprice += '<td>' + USD.description + '</td>';
currentprice += '<td>' + USD.rate + '</td>';
currentprice += '</tr>';
});
$("#current_table").append(currentprice);
})
})
谢谢
2个回答
检查值是否存在,如果值不存在则设置为空字符串。
var currentprice = '';
$.each(json.bpi, function(key, value) {
var USD = value.USD
var symbol = USD.symbol || ""
var description = USD.description || ""
var rate = USD.rate || ""
+= '<tr>';
+= '<td>' + symbol + '</td>';
+= '<td>' + description + '</td>';
+= '<td>' + rate + '</td>';
+= '</tr>';
});
$("#current_table").append(currentprice);
david-giorgi
2020-10-18
您正在循环遍历
json.bpi
,它将为您提供
USD、GBP..etc
,因此只需使用
value.keyname
从 json 对象中获取特定值。
演示代码 :
$(document).ready(function() {
$.getJSON("https://api.coindesk.com/v1/bpi/currentprice.json", function(json) {
var currentprice = '';
$.each(json.bpi, function(key, value) {
currentprice += '<tr>';
currentprice += '<td>' + value.symbol + '</td>';
currentprice += '<td>' + value.description + '</td>';
currentprice += '<td>' + value.rate + '</td>';
currentprice += '</tr>';
});
$("#current_table").append(currentprice);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="current_table" border='1'>
</table>
Swati
2020-10-18