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

如何获取HTML表单值并调用假新闻检测API展示结果?

解决方案

1. 修复输入值获取问题

你的原函数存在变量赋值逻辑错误,正确获取输入框值的方式是读取元素的value属性,同时HTML按钮的点击事件需要补全括号才能触发函数。

修正后的基础函数+HTML

<input type="text" name="check" id="check">
<!-- 补全函数调用的括号 -->
<button onClick="checkFakeNews()" id="btn">Check</button>

<p id="result"></p>

<script>
function checkFakeNews() {
  // 获取输入框元素并读取值
  const text = document.getElementById('check').value;
  console.log(text);
}
</script>

2. 集成假新闻检测API并展示结果

接下来整合API调用逻辑,将返回结果展示到指定的<p>标签中。你需要先在RapidAPI平台获取自己的API密钥,替换代码中的YOUR_RAPIDAPI_KEY:

完整实现代码

<input type="text" name="check" id="check" placeholder="输入新闻标题">
<button onClick="checkFakeNews()" id="btn">Check</button>

<p id="result"></p>

<script>
async function checkFakeNews() {
  const title = document.getElementById('check').value;
  const resultElement = document.getElementById('result');

  // 空输入判断
  if (!title.trim()) {
    resultElement.textContent = '请输入要检测的新闻标题';
    return;
  }

  resultElement.textContent = '检测中...';

  try {
    const response = await fetch('https://fake-news-detection1.p.rapidapi.com/api/v1/fake_news_detection', {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        'X-RapidAPI-Key': 'YOUR_RAPIDAPI_KEY', // 替换为你的RapidAPI密钥
        'X-RapidAPI-Host': 'fake-news-detection1.p.rapidapi.com'
      },
      body: JSON.stringify({ text: title })
    });

    const data = await response.json();
    // 根据API返回结构展示结果,可根据实际返回字段调整
    resultElement.textContent = `检测结果:${data.result},可信度:${data.confidence || '无数据'}`;
  } catch (error) {
    resultElement.textContent = '检测失败,请稍后重试';
    console.error(error);
  }
}
</script>

关键提示

  • 必须替换YOUR_RAPIDAPI_KEY为你在RapidAPI平台申请的有效密钥,否则请求会被拒绝。
  • 若API返回的字段结构不同,可根据实际返回的data对象调整结果展示的代码逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 18:50:31