如何将外部JSON中的数据保存到HTML?
我有一个网站http://api.nbp.pl/api/exchangerates/rates/A/USD?format=json,我只需要从此查询中保存rates.mid
并将其乘以html文件中的PLN值。有人能帮助我吗?
丹尼尔。
答案 0 :(得分:0)
由于我不知道你是否有jQuery,我采用了xhr的例子:https://mathiasbynens.be/notes/xhr-responsetype-json
我们基本上添加了允许我们加载JSON文件的函数getJSON
。
使用data.rates[0].mid
,我们可以访问mid
值(费率是一个数组)。
var getJSON = function(url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('get', url, true);
xhr.onreadystatechange = function() {
var status;
var data;
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
getJSON('https://api.nbp.pl/api/exchangerates/rates/A/USD?format=json', function(data) {
alert(data.rates[0].mid);
}, function(status) {
alert('Something went wrong.');
});

使用jQuery,这将起作用:
$.getJSON('https://api.nbp.pl/api/exchangerates/rates/A/USD?format=json',
function(data){
alert(data.rates[0].mid);
},function(error){
console.log(error);
});
答案 1 :(得分:-1)
<html>
<head>
<script type="text/javascript" > </script>
<script>
$(function() {
var people = [];
$.getJSON('people.json', function(data) {
$.each(data.person, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
"<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "userdata" border="2">
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>City</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
</html>
people.json
{
"person": [
{
"firstName": "Clark",
"lastName": "Kent",
"job": "Reporter",
"roll": 20
},
{
"firstName": "Bruce",
"lastName": "Wayne",
"job": "Playboy",
"roll": 30
},
{
"firstName": "Peter",
"lastName": "Parker",
"job": "Photographer",
"roll": 40
}
]
}
Hope i will help you :)