<body>
<h1>This is a page</h1>
<div id="page"></div>
<script>
fetch("http://dummy.restapiexample.com/api/v1/employees")
.then(response => response.json())
.then(data => {
console.log(data)
document.querySelector("#page").innerText = JSON.stringify(data)
})
</script>
這是我的嘗試,它顯示了所有物件,但我只需要第一個
uj5u.com熱心網友回復:
由于 API 回傳一個具有success和data屬性的物件,我認為您需要第一個data物件,因此第一個員工。
看看在檔案中使用物件,它是 Javascript 中的必備知識。
<body>
<h1>This is a page</h1>
<div id="page"></div>
<script>
fetch('http://dummy.restapiexample.com/api/v1/employees')
.then(response => response.json())
.then(data => {
document.body.innerText = JSON.stringify(data.data[0]);
});
</script>
</body>
uj5u.com熱心網友回復:
<body>
<h1>This is a page</h1>
<div id="page"></div>
<script>
fetch("http://dummy.restapiexample.com/api/v1/employees")
.then(response => response.json())
.then(data => {
console.log(data[0]) //notice the index in data
document.querySelector("#page").innerText =JSON.stringify(data[0])
})
</script>
那將假設資料是一個物件陣列,您可以像在任何陣列中一樣選擇第一個元素。沒有看到將是合乎邏輯的方法的回應結構。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/400271.html
標籤:javascript html 接口 拿来
上一篇:如何在PHP中對API值進行排序
