laravel layui 后台 消息提示 客户端自动轮询
一、后台 layout.blade 里
<script> function jump_msg() { var url = "{{route('admin.message.index')}}"; var tab_id = "user_message"; jumpTab(url,tab_id,'消息中心'); } //获取消息 function getMessages() { var $ = layui.jquery; var _token = $("input[name='_token']").val(); $.ajax({ url:"{{route('admin.get_user_message')}}", data:{ "_token": _token}, type: "post", dataType: "json", success: function (data) { $("#msg_tip").html(''); if(data.code == 0){ $("#message_count").html(data.data.total); $("#msg_tip").html(data.data.msg); layer.open({ skin: 'layui-layer-molv', title: '消息提示', type: 1, content: $("#msg_tip"), area: ['300px', '150px'], offset: 'rb', shade: 0, btn: ['点击进入'], yes: function(index, layero){ layer.close(index); var url = data.data.url+"?msg_id="+data.data.id; var tab_id = "detail_inquiry"; jumpTab(url,tab_id,'点击查看'); } }); }else{ $("#message_count").html(data.data.total); } }, error: function () { } }); } window.setInterval(function(){ getMessages(); },300000); </script>
php 消息接口
public function getUserMessage(Request $request){ $user_id = auth('web')->user()->id; $role_id = auth('web')->user()->role->role_id; //角色id $total = UserMessage::where('status', '=', 0)->orderBy('id', 'desc')->count(); if($total == 0){ return Y::error('暂无消息', array( 'total'=>0 )); } //管理员看数字,弹出 if ($role_id == 1 || $role_id == 13) { $total = UserMessage::where('status', '=', 0)->orderBy('id', 'desc')->count(); if($total == 0){ return Y::error('暂无消息', array( 'total'=>0 )); } $message = UserMessage::where('status', '=', 0)->orderBy('id', 'desc')->first(); if($message){ $data = array( 'total'=> $total, 'msg'=> $message->msg, 'url'=> $message->url, 'id'=> $message->id ); return Y::success('请求成功', $data); } } $total = UserMessage::where('user_id', '=', $user_id)->where('status', '=', 0)->orderBy('id', 'desc')->count(); if($total == 0){ return Y::error('暂无消息', array( 'total'=>0 )); } $message = UserMessage::where('user_id', '=', $user_id)->where('status', '=', 0)->orderBy('id', 'desc')->first(); if($message){ $data = array( 'total'=> $total, 'msg'=> $message->msg, 'url'=> $message->url, 'id'=> $message->id ); return Y::success('请求成功', $data); } return Y::error('暂无消息', array( 'total'=>0 )); }