上一篇
"小王盯着电脑屏幕,手指在键盘上犹豫不决,他刚刚完成了一个数据展示页面,但现在产品经理要求添加删除功能——而且不能刷新整个页面。'难道要重新加载所有数据吗?这也太不优雅了...'小王喃喃自语,这时,他想起了Ajax这个老朋友。"
在传统web开发中,删除数据通常意味着表单提交或链接跳转,整个页面都会刷新,这不仅影响用户体验,还浪费带宽,而Ajax技术允许我们在后台悄悄完成删除操作,只更新必要的部分,让页面保持流畅。
假设我们有一个简单的数据表格:
<table id="data-table"> <thead> <tr> <th>ID</th> <th>用户名</th> <th>操作</th> </tr> </thead> <tbody> <tr data-id="1"> <td>1</td> <td>张三</td> <td><button class="delete-btn">删除</button></td> </tr> <tr data-id="2"> <td>2</td> <td>李四</td> <td><button class="delete-btn">删除</button></td> </tr> <tr data-id="3"> <td>3</td> <td>王五</td> <td><button class="delete-btn">删除</button></td> </tr> </tbody> </table>
如果你使用jQuery库,删除第二行并发送Ajax请求非常简单:
$(document).ready(function() { // 为所有删除按钮绑定点击事件 $('.delete-btn').click(function() { // 获取当前行的tr元素 var $row = $(this).closest('tr'); var rowId = $row.data('id'); // 获取数据ID // 确认对话框 if(confirm('确定要删除这行数据吗?')) { // 发送Ajax请求 $.ajax({ url: '/api/delete-data', method: 'POST', data: { id: rowId }, success: function(response) { if(response.success) { // 删除成功,移除表格行 $row.remove(); console.log('删除成功!'); } else { alert('删除失败:' + response.message); } }, error: function() { alert('请求失败,请检查网络'); } }); } }); });
如果你更喜欢原生JS,也可以这样实现:
document.addEventListener('DOMContentLoaded', function() { const deleteButtons = document.querySelectorAll('.delete-btn'); deleteButtons.forEach(button => { button.addEventListener('click', function() { const row = this.closest('tr'); const rowId = row.dataset.id; if(confirm('确定要删除这行数据吗?')) { const xhr = new XMLHttpRequest(); xhr.open('POST', '/api/delete-data', true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if(xhr.status === 200) { const response = JSON.parse(xhr.responseText); if(response.success) { row.remove(); console.log('删除成功!'); } else { alert('删除失败:' + response.message); } } else { alert('请求失败,状态码:' + xhr.status); } }; xhr.onerror = function() { alert('网络错误,请求失败'); }; xhr.send(JSON.stringify({ id: rowId })); } }); }); });
data-id属性的妙用:我们在tr元素上添加了data-id属性,这样能轻松获取要删除的数据ID
用户体验考虑:添加了确认对话框,防止误操作
错误处理:对网络请求失败和业务逻辑失败都做了处理
性能优化:只删除单行而不是刷新整个表格
让删除操作更平滑:
// jQuery版本 $row.fadeOut(300, function() { $(this).remove(); }); // 原生JS版本 row.style.transition = 'opacity 0.3s'; row.style.opacity = '0'; setTimeout(() => row.remove(), 300);
如果你想批量删除多行,可以这样实现:
// 添加复选框到每行 // HTML修改略 $('#batch-delete-btn').click(function() { const selectedIds = []; $('input[type="checkbox"]:checked').each(function() { selectedIds.push($(this).closest('tr').data('id')); }); if(selectedIds.length === 0) { alert('请至少选择一项'); return; } if(confirm(`确定要删除选中的${selectedIds.length}项吗?`)) { $.ajax({ url: '/api/batch-delete', method: 'POST', data: { ids: selectedIds }, success: function(response) { if(response.success) { $('input[type="checkbox"]:checked').closest('tr').remove(); alert('批量删除成功!'); } } }); } });
问题1:删除后表格空了怎么办?
可以添加空状态提示:
success: function(response) { if(response.success) { $row.remove(); if($('#data-table tbody tr').length === 0) { $('#data-table tbody').html('<tr><td colspan="3">暂无数据</td></tr>'); } } }
问题2:如何防止重复提交?
在发送请求时禁用按钮:
$row.find('.delete-btn').prop('disabled', true); // 请求完成后记得恢复
通过Ajax实现行删除功能,我们不仅提升了用户体验,还减少了不必要的网络请求,记住几个关键点:
小王可以轻松实现产品经理的需求了,而且效果比预期的还要好!Ajax技术在现代web开发中仍然是不可或缺的利器,掌握它能让你在前端开发中游刃有余。 参考2025年8月前端开发最佳实践)
本文由 魏白容 于2025-08-01发表在【云服务器提供商】,文中图片由(魏白容)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/503388.html
发表评论