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

如何通过无页面刷新的POST请求更新Phone模型的assigned字段

解决无刷新更新Phone模型assigned字段的问题

看起来你已经找对了方向——用AJAX实现无页面刷新更新数据库,但你的代码里有几个关键问题导致没能成功,我帮你梳理并修正一下:

原代码的核心问题

  • URL占位符未替换:http.open("POST","employee/edit/{id}",true)里的{id}是硬编码的占位符,后端无法识别实际的员工ID,需要替换为当前页面的员工ID值
  • 参数传递不明确:你直接发送了'false',但后端不知道这个值对应哪个字段,需要指定参数名(比如assigned=false)
  • DOM更新方式错误:document.getElementById("assignPhone").innerHTML是用来更新元素内容的,对于input元素应该用.value来设置其值
  • 提交按钮的跳转问题:原submit按钮会触发默认的表单提交导致页面跳转,需要改成普通按钮或者阻止默认行为后用AJAX提交

修正后的实现方案

1. 前端JavaScript代码

首先,我们需要先获取当前页面的员工ID(从readonly的input里),然后修正AJAX请求:

function setBooleanForCurrentPhone() {
  // 获取当前员工ID
  const employeeId = document.querySelector('[th\\:field="*{id}"]').value;
  const assignedValue = 'false'; // 你要设置的assigned值
  
  const http = new XMLHttpRequest();
  http.onreadystatechange = function () {
    if (this.readyState === 4 && this.status === 200) {
      // 成功更新后,同步更新隐藏input的值
      document.getElementById("assignPhone").value = assignedValue;
      console.log('Phone assigned status updated successfully');
    } else if (this.readyState === 4 && this.status !== 200) {
      console.error('Failed to update phone status');
    }
  };
  
  // 替换URL里的{id}为实际员工ID
  const url = `employee/edit/${employeeId}`;
  http.open("POST", url, true);
  // 设置正确的请求头,并且指定参数名
  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  // 发送带字段名的参数
  http.send(`assigned=${assignedValue}`);
}

// 处理提交按钮的无刷新提交(如果需要保存其他员工信息)
function setBooleanForPhone(event) {
  // 阻止默认的表单提交跳转
  event.preventDefault();
  
  // 这里可以添加其他表单字段的收集逻辑,或者直接调用上面的AJAX函数
  // 如果需要更新整个员工对象,也可以用FormData来收集表单数据
  const form = document.querySelector('form');
  const formData = new FormData(form);
  
  const employeeId = document.querySelector('[th\\:field="*{id}"]').value;
  const http = new XMLHttpRequest();
  http.onreadystatechange = function () {
    if (this.readyState === 4 && this.status === 200) {
      alert('Employee info saved successfully');
    }
  };
  
  http.open("POST", `employee/edit/${employeeId}`, true);
  http.send(formData);
}

2. 修正HTML中的提交按钮

把原submit按钮的onclick事件加上event参数,阻止默认跳转:

<tr>
  <td colspan="2">
    <button onclick="setBooleanForPhone(event)" type="submit">Save</button>
  </td>
</tr>

3. 后端接口注意事项

你的后端employee/edit/{id}接口需要:

  • 接收POST请求中的assigned参数
  • 根据员工ID找到对应的Phone对象,更新其assigned字段为false
  • 保存到数据库后,返回200状态码(可以返回更新后的状态或者空响应)

额外优化建议

  • 可以用更现代的fetch API替代XMLHttpRequest,代码更简洁:
async function setBooleanForCurrentPhone() {
  const employeeId = document.querySelector('[th\\:field="*{id}"]').value;
  const assignedValue = 'false';
  
  try {
    const response = await fetch(`employee/edit/${employeeId}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: `assigned=${assignedValue}`
    });
    
    if (response.ok) {
      document.getElementById("assignPhone").value = assignedValue;
      console.log('Status updated');
    } else {
      throw new Error('Update failed');
    }
  } catch (error) {
    console.error(error);
  }
}

这样就能实现无页面刷新更新数据库中的Phone模型assigned字段了,同时解决提交按钮跳转的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:07:03