我一直在尝试从"当前新闻来源"中提取数据。使用Javascript以JSON结构的API。我现在正处于测试阶段。
点击我想让我的HTML元素命名为"title"从新闻JSON文件更新为标题。这是我到目前为止所掌握的……
HTML
<h3 class="title text-center" id="title" name="title">Russia accuses US of interfering in vote</h3>
<button type="button" class="btn btn-outline-dark text-white bg-muted" id="searchButton">Search</button>
Javascript
const title = document.getElementById("title");
const searchButton = document.getElementById("searchButton");
searchButton.addEventListener("click", getRandomTitle)
function getRandomTitle() {
fetch('https://api.currentsapi.services/v1/latest-news?q=keywords=Biden&apiKey=12345678910')
.then(res => res.json())
.then(data => {
title.innerHTML = data.news.title
});
}
JSON文件
{
"status": "ok",
"news": [
{
"id": "4e67842f-018d-4744-aa02-d21da55c278d",
"title": "Early Matter Domination from Long-Lived Particles in the Visible Sector. (arXiv:2108.13136v2 [hep-ph] UPDATED)"
...
data.news
是一个对象数组,要访问特定的标题必须使用相应的索引。
另外,我建议您使用HTMLElement.innerText
或Node.textContent
将纯文本(不是htmlString)设置为HTML元素:
title.textContent = data.news[0].title; // get the title from first news object
从JSON文件,它看起来像data.news
是一个数组。
试试data.news[0].title
尝试使用data.news[0].title
,因为似乎您正在获得data.news
的结果对象数组
function getRandomTitle() {
fetch('https://api.currentsapi.services/v1/latest-news?q=keywords=Biden&apiKey=12345678910')
.then(res => res.json())
.then(data => {
title.innerHTML = data.news[0].title // Specify the index for the array
});