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

如何用浏览器端JavaScript实现指定CURL请求及分页功能?

问题与代码修正

需要将以下CURL请求转为浏览器端JavaScript代码,要求:

  • CIK为用户输入的变量
  • 通过递增from参数实现分页

原CURL请求

curl -XPOST -H "Content-type: application/json" -d '{
  "query": "cik:<CIK_VALUE_FROM_USER> AND formType:\"4\"",
  "from": "0",
  "size": "10",
  "sort": [{ "filedAt": { "order": "desc" } }]
}' 'https://api.sec-api.io?token=<MY_CONSTANT_TOKEN_VALUE>'

你写的代码存在的问题

  1. 未获取用户输入的CIK值,仍使用硬编码占位符
  2. fetch的body用了queryBody.toString(),会把对象转为无效的[object Object],应该用JSON.stringify()序列化JSON
  3. 未实现分页逻辑,没有维护和递增from参数
  4. 表单按钮点击会触发默认提交行为,导致页面刷新
  5. 仅alert响应状态文本,未展示实际返回的数据
  6. 缺少错误处理逻辑

修正后的完整代码

<!DOCTYPE html>
<html>
<head>
  <title>Insider Trading</title>
  <style>
    .result-container { margin-top: 20px; padding: 10px; border: 1px solid #eee; }
    .pagination { margin-top: 10px; }
    button { margin-right: 5px; }
    .error { color: red; }
  </style>
</head>
<body>
  <form id="cik-form">
    <label>CIK:</label>
    <input type="text" name="cik" placeholder="输入CIK编号" required>
    <button type="submit">查询第一页</button>
  </form>

  <div class="pagination" style="display: none;">
    <button id="prev-page">上一页</button>
    <button id="next-page">下一页</button>
    <span>当前页码: <span id="current-page">1</span></span>
  </div>

  <div class="result-container">
    <h3>查询结果</h3>
    <div id="result-content"></div>
    <div id="error-message" class="error"></div>
  </div>

  <script>
    // 配置项
    const API_TOKEN = '<MY_CONSTANT_TOKEN_VALUE>'; // 替换成你的实际token
    const PAGE_SIZE = 10; // 每页条数,和原curl一致

    // 分页状态
    let currentFrom = 0;
    let currentCik = '';

    // 获取DOM元素
    const form = document.getElementById('cik-form');
    const prevBtn = document.getElementById('prev-page');
    const nextBtn = document.getElementById('next-page');
    const currentPageSpan = document.getElementById('current-page');
    const resultContent = document.getElementById('result-content');
    const errorMsg = document.getElementById('error-message');
    const pagination = document.querySelector('.pagination');

    // 发送API请求的核心函数
    async function fetchData(cik, from) {
      errorMsg.textContent = '';
      resultContent.innerHTML = '加载中...';

      const queryBody = {
        query: `cik:${cik} AND formType:"4"`,
        from: from.toString(),
        size: PAGE_SIZE.toString(),
        sort: [{ filedAt: { order: 'desc' } }]
      };

      try {
        const response = await fetch(`https://api.sec-api.io?token=${API_TOKEN}`, {
          method: 'POST',
          body: JSON.stringify(queryBody),
          headers: { 'Content-Type': 'application/json' }
        });

        if (!response.ok) {
          throw new Error(`API请求失败: ${response.statusText}`);
        }

        const data = await response.json();
        displayResult(data);
        // 更新分页状态
        currentFrom = from;
        currentCik = cik;
        currentPageSpan.textContent = Math.floor(from / PAGE_SIZE) + 1;
        pagination.style.display = 'block';
        // 禁用上一页如果是第一页
        prevBtn.disabled = from === 0;
      } catch (err) {
        errorMsg.textContent = err.message;
        resultContent.innerHTML = '';
      }
    }

    // 展示查询结果
    function displayResult(data) {
      if (!data.hits || data.hits.hits.length === 0) {
        resultContent.innerHTML = '没有找到匹配的数据';
        return;
      }

      // 把结果转成列表展示
      const list = document.createElement('ul');
      data.hits.hits.forEach(item => {
        const li = document.createElement('li');
        li.innerHTML = `
          <strong>公司:</strong> ${item._source.name || '未知'}<br>
          <strong>提交时间:</strong> ${new Date(item._source.filedAt).toLocaleString()}<br>
          <strong>表单类型:</strong> ${item._source.formType}<br>
          <hr>
        `;
        list.appendChild(li);
      });
      resultContent.innerHTML = '';
      resultContent.appendChild(list);
    }

    // 表单提交事件(查询第一页)
    form.addEventListener('submit', (e) => {
      e.preventDefault(); // 阻止页面刷新
      const cikInput = form.querySelector('input[name="cik"]');
      const cik = cikInput.value.trim();
      if (cik) {
        fetchData(cik, 0);
      }
    });

    // 上一页按钮事件
    prevBtn.addEventListener('click', () => {
      if (currentFrom > 0) {
        fetchData(currentCik, currentFrom - PAGE_SIZE);
      }
    });

    // 下一页按钮事件
    nextBtn.addEventListener('click', () => {
      fetchData(currentCik, currentFrom + PAGE_SIZE);
    });
  </script>
</body>
</html>

关键修正说明

  • 新增了用户CIK输入的获取逻辑,用模板字符串动态生成查询语句
  • 用JSON.stringify()正确序列化请求体,符合API要求的JSON格式
  • 维护了currentFrom变量来跟踪分页位置,实现上/下一页的递增/递减
  • 阻止了表单默认提交行为,避免页面刷新
  • 增加了错误处理和加载状态提示
  • 把返回的数据以列表形式展示,方便查看
  • 分页按钮会根据当前页码自动禁用上一页(第一页时)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 01:47:34