如何在JavaScript函数中调用Ajax实现表格行数据提交
完善表格行删除的Ajax提交功能
没问题,我来帮你搞定这个需求!你已经正确获取到了要删除行的ID值,接下来只需要在deleteRow函数中添加Ajax请求,把这个ID提交到指定的后端URL就可以了。下面给你两种常用的实现方案:
方案1:使用现代的Fetch API(推荐)
Fetch API是ES6+的标准,语法更简洁,支持Promise,处理异步请求更方便:
<script> function deleteRow(btn) { var row = btn.parentNode.parentNode; const id = row.cells[0].textContent; // 发送Fetch请求 fetch('你的指定URL', { method: 'POST', // 或者根据后端要求用DELETE headers: { 'Content-Type': 'application/json', // 如果后端需要CSRF令牌,这里也要加上对应的头部 }, body: JSON.stringify({ id: id }) // 把ID转为JSON格式提交 }) .then(response => { if (!response.ok) { throw new Error('请求失败'); } return response.json(); // 如果后端返回JSON数据 }) .then(data => { // 请求成功后的处理,比如移除当前行 row.remove(); console.log('删除成功:', data); }) .catch(error => { console.error('删除失败:', error); alert('删除失败,请稍后重试'); }); } </script> <body> <table> <tr> <th>Id</th> <th>Lastname</th> <th>Firstname</th> <th></th> </tr> <tr> <td>122</td> <td>Jackson</td> <td>Evans</td> <td><button type="button" onclick="deleteRow(this)">Delete row</button></td> </tr> </table> </body>
方案2:使用传统的XMLHttpRequest
如果需要兼容旧版浏览器,可以用原生XHR:
<script> function deleteRow(btn) { var row = btn.parentNode.parentNode; const id = row.cells[0].textContent; // 创建XHR对象 const xhr = new XMLHttpRequest(); xhr.open('POST', '你的指定URL', true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { // 请求成功,移除当前行 row.remove(); const data = JSON.parse(xhr.responseText); console.log('删除成功:', data); } else { console.error('删除失败,状态码:', xhr.status); alert('删除失败,请稍后重试'); } }; xhr.onerror = function() { console.error('网络请求失败'); alert('网络异常,请检查连接'); }; // 发送请求数据 xhr.send(JSON.stringify({ id: id })); } </script> <body> <table> <tr> <th>Id</th> <th>Lastname</th> <th>Firstname</th> <th></th> </tr> <tr> <td>122</td> <td>Jackson</td> <td>Evans</td> <td><button type="button" onclick="deleteRow(this)">Delete row</button></td> </tr> </table> </body>
注意事项:
- 把代码中的
你的指定URL替换成实际的后端接口地址 - 根据后端要求选择请求方法(
POST或DELETE) - 如果后端需要表单格式的数据,把
Content-Type改为application/x-www-form-urlencoded,并把body改为id=' + id这种格式 - 请求成功后别忘了移除当前行,提升用户体验
内容的提问来源于stack exchange,提问作者DougKruger
相关产品推荐
相关产品推荐

