Laravel 5.5+Bootstrap3:拦截可关闭Alert关闭事件并Ajax更新模型状态
嘿,这个需求其实不难实现,咱们一步步来搞定它:
步骤1:修改Alert关闭按钮的HTML
首先,你需要给关闭按钮加上一个用来标识对应Notification的属性,比如data-notification-id,这样后面JS能准确拿到要更新的记录ID。修改后的按钮代码如下:
<button type="button" class="close" data-dismiss="alert" aria-hidden="true" data-notification-id="{{ $notification->id }}"> <i class="fa fa-times"></i> </button>
这里的{{ $notification->id }}就是你从Laravel视图里传递过来的Notification模型ID。
步骤2:编写JavaScript拦截关闭事件并发送Ajax
Bootstrap 3的Alert组件提供了close.bs.alert事件——这个事件会在Alert真正关闭之前触发,刚好用来拦截默认行为。咱们用jQuery(Bootstrap 3依赖它)来写这段逻辑:
$(document).on('close.bs.alert', '.alert', function(e) { // 阻止Alert默认的关闭行为 e.preventDefault(); // 获取当前Notification的ID const notificationId = $(this).find('.close').data('notification-id'); // 发送Ajax请求到Laravel后端 $.ajax({ url: `/notifications/${notificationId}/mark-as-read`, // 请对应你自己的后端路由 method: 'POST', data: { _token: '{{ csrf_token() }}', // Laravel必须的CSRF令牌,防止跨站请求伪造 status: 0 }, success: function(response) { // 更新成功后,手动关闭Alert $(this).alert('close'); // 可选:添加成功提示,比如console.log('Notification状态已更新') }.bind(this), // 绑定上下文,确保success回调里能正确获取当前Alert元素 error: function(xhr) { // 处理请求失败的情况,比如提示用户 console.error('更新Notification状态失败:', xhr.responseText); // 可根据需求选择是否关闭Alert } }); });
注意bind(this)很关键,不然success回调里的this就不是当前的Alert元素了;另外CSRF令牌一定要带上,不然Laravel会直接拒绝请求。
步骤3:配置Laravel的路由和控制器
首先在routes/web.php(如果用API路由就写在api.php)里添加一条路由:
// 用POST请求更新Notification状态 Route::post('/notifications/{notification}/mark-as-read', 'NotificationController@markAsRead')->name('notifications.mark-as-read');
然后在app/Http/Controllers/NotificationController.php里添加对应的控制器方法:
public function markAsRead(Notification $notification) { // 可选:验证当前用户是否有权限操作这条Notification if ($notification->user_id !== auth()->id()) { return response()->json(['success' => false, 'message' => '无权限操作'], 403); } // 更新status为0 $notification->update(['status' => 0]); // 返回JSON响应告知前端更新成功 return response()->json(['success' => true, 'message' => 'Notification状态已更新']); }
这里用到了Laravel的路由模型绑定,框架会自动根据URL里的{notification}参数找到对应的Notification实例,非常省心。
额外注意事项
- 确保你的Alert元素带有
.alert类,否则JS里的选择器$('.alert')会找不到目标元素; - 如果你的Notification是用户专属的,一定要加上权限验证逻辑,防止恶意请求修改不属于当前用户的记录。
这样一套流程走下来,用户点击关闭按钮时,会先发送Ajax请求更新数据库中的status,成功后再关闭Alert,完美实现你的需求~
内容的提问来源于stack exchange,提问作者natas
相关产品推荐
相关产品推荐

