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

如何传递表单输入至对象数组?解决addNewPlayer固定值提交问题

问题解决方法

1. 修复addNewPlayer函数(核心问题)

你现在的addNewPlayer函数虽然接收了playerObj参数,但完全没用到它,而是硬编码了固定的name和breed值——这就是为什么提交后总是添加"Rufus"的原因。直接把JSON.stringify里的固定值换成传入的playerObj即可:

export const addNewPlayer = async (playerObj) => {
  try {
    const response = await fetch(
      `${APIURL}players/`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        // 替换为传入的用户数据对象
        body: JSON.stringify(playerObj),
      }
    );
    const result = await response.json();
    console.log(result);
    return result;
  } catch (err) {
    console.error(err);
    throw err;
  }
};

2. 理解playerObj的用途

这个参数就是用来接收外部传入的用户输入数据的——比如你从表单里拿到的playerData,通过把它传给addNewPlayer,函数就能动态处理不同的输入,而不是只能添加固定的那条数据。

3. 调整表单提交逻辑的顺序

你现在的代码是先获取旧列表渲染,再添加新数据,导致新内容不会显示。应该先完成添加操作,再刷新列表:

let form = document.querySelector('#new-player-form > form');
form.addEventListener('submit', async (event) => {
  event.preventDefault();
  
  let playerData = {
    name: form.elements.name.value.trim(),
    breed: form.elements.breed.value.trim()
  };
  console.log(playerData);

  // 非空校验,避免空值触发API报错
  if (!playerData.name || !playerData.breed) {
    alert('请填写完整的姓名和犬种');
    return;
  }

  try {
    // 先添加新数据
    await addNewPlayer(playerData);
    // 再获取最新列表并渲染
    const players = await fetchAllPlayers();
    renderAllPlayers(players);
    // 重置表单
    renderNewPlayerForm();
  } catch (err) {
    console.error('添加失败:', err);
    alert('添加失败,请重试');
  }
});

4. 解决空值报错问题

你之前设为空字符串报错,是因为API要求name和breed为必填字段。上面代码里的非空校验,能确保用户输入完整内容后再调用接口,从源头避免这个错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:15:44