所以,我在節點服務器上有一個 http://localhost:3000/community 端點,如果呼叫 GET 方法,它會向我顯示 3 個不同的物件,其中包含有關“用戶”的資訊。
例如 :
[
{
"avatar": "http://localhost:3000/avatars/avatar1.png",
"firstName": "Mary",
"lastName": "Smith",
"position": "Lead Designer at Company Name"
},
{
"avatar": "http://localhost:3000/avatars/avatar2.png",
"firstName": "Bill",
"lastName": "Filler",
"position": "Lead Engineer at Company Name"
},
{
"avatar": "http://localhost:3000/avatars/avatar3.png",
"firstName": "Tim",
"lastName": "Gates",
"position": "CEO at Company Name"
}
]

任務不是獲取顯示在控制臺中的資訊,而是通過以下方式顯示在網站上的創建部分中:

Mary Smith、John Smyth 和 Maryanne Smytch 是 json 檔案中的名字,他們的位置也在 json 檔案中,頭像也是。
我的問題是,因為我是 javascript 新手并使用 fetch,如何獲取這些資料并將它們放入 DOM 中?該部分應在 javascript 中動態制作。我只需要剪下一個代碼,因為我搜索了整個互聯網,但我沒有找到如何從 json 中單獨獲取資料并將它們像頭像、標題、文本區域或其他東西一樣放置。
請幫忙,提前致謝!
我的提取功能:
const sendHttpRequest = (method, url, data) => {
return fetch(url, {
method: method,
body: JSON.stringify(data),
headers: data ? {
'Content-Type': 'application/json'
} : {}
}).then(response => {
if (response.status >= 400) {
return response.json().then(errResData => {
const error = new Error('Something went wrong!');
error.data = errResData;
throw error;
});
}
return response.json();
});
};
const getCommunity = () => {
sendHttpRequest('GET','http://localhost:8080/community')
.then(communityResponse =>{
console.log(communityResponse);
}).catch(err =>{
console.log(err,err.data);
});
}
來自服務器的社區路由:
const express = require('express');
const router = express.Router();
const {randomNumber} = require('../utils');
const FileStorage = require('../services/FileStorage');
/* GET /community */
router.get('/', async function(req, res) {
try {
const result = await FileStorage.readJsonFile(`community/${randomNumber(1, 3)}.json`);
await res.json(result);
} catch (e) {
console.log(e);
res.status(500).send('Internal error');
}
});
module.exports = router;
uj5u.com熱心網友回復:
您可以在回應陣列中映射并將資料附加到正文中,如下所示:
for (let i=0;i<items.length;i ) {
// appending your elements to the body :
document.body.appendChild(items[i]);}
你可以像這樣操作 DOM:
var node = document.createElement("LI"); // Create a <li> node
var textnode = document.createTextNode("Water"); // Create a text node
node.appendChild(textnode); // Append the text to <li>
document.getElementById("myList").appendChild(node);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/388108.html
標籤:javascript html dom 拿来
