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

创建车牌输入表单并基于动态查询字符串请求API获取数据

实现车牌号查询表单与动态API请求

下面是一套完整的前端实现方案,包含表单构建、动态API请求发起和结果展示:

1. HTML 表单结构

先搭建基础的输入表单和结果展示区域:

<form id="vrmSearchForm">
  <label for="vrmInput">车牌号:</label>
  <input type="text" id="vrmInput" placeholder="请输入车牌号" required>
  <button type="submit">查询数据</button>
</form>

<div id="resultContainer" style="margin-top: 20px; display: none;">
  <h3>查询结果</h3>
  <pre id="resultContent"></pre>
</div>

2. JavaScript 逻辑处理

编写脚本监听表单提交,动态拼接API请求地址并获取数据:

const form = document.getElementById('vrmSearchForm');
const resultContainer = document.getElementById('resultContainer');
const resultContent = document.getElementById('resultContent');

form.addEventListener('submit', async (e) => {
  e.preventDefault(); // 阻止表单默认提交行为
  
  const vrm = document.getElementById('vrmInput').value.trim();
  if (!vrm) return;

  // 构建带动态车牌号的API请求地址,对车牌号做URL编码避免特殊字符问题
  const apiUrl = `https://app.website.co.uk/api/datapackage/data?v=2&api_nullitems=1&auth_apikey=xxx&key_VRM=${encodeURIComponent(vrm)}`;

  try {
    // 发起API请求
    const response = await fetch(apiUrl);
    if (!response.ok) throw new Error(`请求失败:${response.status}`);
    
    const data = await response.json();
    
    // 格式化展示结果
    resultContent.textContent = JSON.stringify(data, null, 2);
    resultContainer.style.display = 'block';
  } catch (error) {
    // 错误提示
    resultContent.textContent = `查询出错:${error.message}`;
    resultContainer.style.display = 'block';
  }
});

关键注意事项

  • API密钥安全:直接在前端代码中暴露auth_apikey存在被盗用的风险,建议通过后端服务转发请求,由后端统一处理API密钥和请求逻辑。
  • 输入校验:可以添加车牌号格式校验(比如正则表达式),提前拦截无效格式的输入,避免无效请求。
  • 错误扩展:可根据需求补充网络异常、无数据返回等场景的自定义提示,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:40:25