You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript调用新闻API拉取数据并渲染到HTML元素问题咨询

问题分析
  • API返回的news字段是数组类型,直接读取data.news.title会得到undefined,数组本身不存在title属性,需要先指定数组下标才能获取单条新闻的title。
  • 请求URL的参数格式错误,原URL中?q=keywords=Biden不符合接口参数规范,Currents API的最新新闻接口筛选关键词直接用keywords作为参数名,无需额外加q=前缀。
  • 缺少异常处理逻辑,接口请求失败、返回异常状态、news数组为空的场景没有做兼容,容易触发页面报错。
  • 使用innerHTML渲染新闻标题存在XSS安全风险,建议替换为textContent。
修复方案

你的HTML代码无需改动,仅需要调整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?keywords=Biden&apiKey=12345678910')
    .then(res => {
        // 校验请求状态
        if (!res.ok) throw new Error('接口请求异常')
        return res.json()
    })
    .then(data => {
        // 校验返回结果合法性
        if (data.status === 'ok' && Array.isArray(data.news) && data.news.length > 0) {
            // 取第一条新闻的标题
            title.textContent = data.news[0].title
            // 如果需要随机取新闻标题,把上面一行替换为下面两行即可
            // const randomIndex = Math.floor(Math.random() * data.news.length)
            // title.textContent = data.news[randomIndex].title
        } else {
            title.textContent = '暂无相关新闻'
        }
    })
    // 捕获所有异常
    .catch(err => {
        title.textContent = '新闻加载失败,请稍后重试'
        console.error('请求错误:', err)
    })
}

内容的提问来源于stack exchange,提问作者user16645351

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 12:51:03