【发布时间】:2021-05-07 22:44:40
【问题描述】:
我正在尝试获取 JSON 响应并将它们显示在我预设的 HTML 元素中。我正在使用graphql(由datocms提供)。
API 浏览器显示我的模型:
query MyQuery {
allNews {
id
newsTitle
newsExcerpt
newsContent
newsCategory
}
}
返回:
{
"data": {
"allNews": [
{
"id": "21003677",
"newsTitle": "The amazing news",
"newsExcerpt": "The amazing news to waste your afternoon.",
"newsContent": "\nThe amazing news is unlike other news to waste your afternoon. It indeed wastes your afternoon in a way unimaginable, never before achieved.\n\nThe News consist of fake news and Trumpian staple conspiracies. ",
"newsCategory": "News"
}
]
}
}
获取:
const token = 'the_token_here';
fetch(
'https://graphql.datocms.com/',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify({
query: '{ allNews { newsTitle } }'
}),
}
)
.then(res => res.json())
.then((res) => {
console.log(res.data)
})
.catch((error) => {
console.log(error);
});
加载静态 HTML 页面时,我想在 HTML 预设元素中显示 JSON 响应:
<h4 class="news--title">$(newsTitle.name)</h4>
<div class="news--description">${newsContent.name}</div>
是否可以使用 vanilla javascript,以及如何使用?
另外,如果响应不止一个(例如,10 个响应)并且我有四个这样的元素组,那么四个 JSON 响应(基于四个最大的 ID 号)是否可以迭代到四个 HTML 元素,如何?
对不起,如果问题是愚蠢的或已在其他地方提出和回答。我开始学习 javascript,之前从未使用过 API 调用/JSON。
【问题讨论】:
标签: javascript json graphql