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

点击按钮触发fetch请求无响应,无法传递data-id到getCarDetails.php

问题根因

你的代码核心错误是fetch请求的配置项参数名写错了,提交POST请求体的正确属性名为body,你写的data是无效参数,因此car_id根本没有发送给后端,导致请求无响应。
另外还要确认你的按钮已经绑定了点击事件触发loadCarDetails函数,否则点击不会触发逻辑。

修正后的完整代码

JS代码

// 页面加载完成后给所有带data-id的btn按钮绑定点击事件
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('.btn[data-id]').forEach(btn => {
    btn.addEventListener('click', loadCarDetails);
  });
});

function loadCarDetails(event) {
  const id = event.currentTarget.getAttribute("data-id");
  const data = new FormData();
  data.append("car_id", id);
  fetch("getCarDetails.php", {
      method: "POST",
      body: data // 此处将错误的data参数名改为正确的body
    })
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
      }
      return response.json();
    })
    .then(carDetails => {
      // 你的业务逻辑,可先加打印验证数据返回
      console.log('车辆详情:', carDetails);
    })
    .catch(error => {
      // 加错误打印方便定位问题
      console.error('请求出错:', error);
    });
}

HTML可选修改方案

如果你不想用JS动态绑定事件,也可以直接给button添加onclick属性手动绑定:

<div class="car-item">
  <div class="row">
    <p>Ford Fiesta</p>
  </div>
  <div class="row">
    <button type="button" class="btn" data-id="1" onclick="loadCarDetails(event)">View</button>
  </div>
</div>

内容的提问来源于stack exchange,提问作者George Austin Bradley

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:24:01