这是我第一次尝试使用简单的API并无法获得良好的结果。我从这里使用了一个示例:Write something that can read this API Url 结果是,我所做的每项更改都给了我4个,而控制台中没有任何更改。 拜托,你能给我个提示吗?
谢谢!
<!DOCTYPE html>
<html>
<body>
first
<div id="fastest">
<script> fetch("https://bitcoinfees.earn.com/api/v1/fees/recommended") // Call the fetch function passing the url of the API as a parameter
.then((resp) => resp.json()) // Transform the data into json
.then(function(data) {
// Your code for handling the data you get from the API
document.write(data.fastestFee); //And since it is just an object you can access any value like this
})
.catch(function(err) {
// This is where you run code if the server returns any errors (optional)
console.log(err)
});
</script>
</div>
</br>second
<div id="30">
<script> fetch("https://bitcoinfees.earn.com/api/v1/fees/recommended") // Call the fetch function passing the url of the API as a parameter
.then((resp) => resp.json()) // Transform the data into json
.then(function(data) {
// Your code for handling the data you get from the API
document.write(data.halfHourFee); //And since it is just an object you can access any value like this
})
.catch(function(err) {
// This is where you run code if the server returns any errors (optional)
console.log(err)
});
</script>
</div>
</br>3th
<div id="60">
<script>
fetch("https://bitcoinfees.earn.com/api/v1/fees/recommended") // Call the fetch function passing the url of the API as a parameter
.then((resp) => resp.json()) // Transform the data into json
.then(function(data) {
// Your code for handling the data you get from the API
document.write(data.hourFee); //And since it is just an object you can access any value like this
})
.catch(function(err) {
// This is where you run code if the server returns any errors (optional)
console.log(err)
});
</script>
</div>
</body>
</html>
答案 0 :(得分:0)
使用document.write
,您将用api响应的值替换现有的html元素。
我重新整理了一些代码,将js放在一个函数中,并用document.write
替换了document.getElementById(elemId).textContent
,它设置了所选元素的当前文本。结果如下:
// Call the method passing the 3 possible values
getFee("fastest");
getFee("halfHour");
getFee("hour");
function getFee(type) {
fetch("https://bitcoinfees.earn.com/api/v1/fees/recommended") // Call the fetch function passing the url of the API as a parameter
.then((resp) => resp.json()) // Transform the data into json
.then(function(data) {
// Your code for handling the data you get from the API
if (type === "fastest") {
document.getElementById("fastest").textContent = data.fastestFee;
} else if (type === "halfHour") {
document.getElementById("30").textContent = data.halfHourFee;
} else if (type === "hour") {
document.getElementById("60").textContent = data.hourFee;
}
})
.catch(function(err) {
// This is where you run code if the server returns any errors (optional)
console.log(err)
});
}
<span>fastest</span>
<div id="fastest">
</div>
<br>
<span>halfHour</span>
<div id="30">
</div>
<br>
<span>Hour</span>
<div id="60">
</div>