我正在做一个laravel项目,我想通过ajax调用加载通知。我写了一个代码来做到这一点。这是我的ajax电话。
$(document).ready(function () {
$('#notificationBar').on('click', function () {
getNotifications();
});
function getNotifications(){
var getNotificationURL = '{{ route('getNotifications') }}';
var token = '{{ Session::token() }}';
$.ajax({
method: 'post',
url : getNotificationURL,
data : {
_token : token
},
success:function (data) {
if(data === null){
}else{
$('#notificationBar').find('#notificationDropDown').find('#tempId').append('<a style="background:#e0e0d1; margin:2px 2px;" href="'+data.username+'"><img src="'+data.url+'" class="w3-circle" style="height:40px;width:40px;margin:4px 4px;" alt="Avatar"> <b> '+data.name+'</b> '+data.msg+'</a>');
}
}
});
}
});
这是我的路线
Route::post('getnotifications', [
'uses' => 'NotificationController@getNotifications',
'as' => 'getNotifications'
]);
路由将在通知控制器中定向到此方法
public function getNotifications(Request $request){
$noti = DB::table('notifications')->where('accepter', Auth::user()->id)->where('status', 1)->where('ajax_call',true)->where('important',true)->first();
if(count($noti)>0){
$new_noti = Notifications::find($noti->id);
$new_noti->ajax_call = false;
$new_noti->update();
$notification = DB::table('notifications')->leftjoin('users','users.id','notifications.current_user')->where('id', $noti->id)->first();
$pro_ulr = asset('/img/'.$notification->pic);
$arr = array(
"username" => $notification->username,
"url" => $pro_ulr,
"name" => $notification->name,
"msg" => $notification->msg
);
return response()->json($arr);
}else{
return null;
}
}
我的问题是此功能无法正常运行。数据库表未更新,并且json似乎为空。我的代码有问题吗?
答案 0 :(得分:1)
我已经更新了您控制器的操作代码,希望这可以解决您的问题:
public function getNotifications(Request $request)
{
$notifications = Notifications::where('accepter', Auth::user()->id)->where('status', 1)->where('ajax_call', true)->where('important', true)->get();
if ( $notifications->count() === 0 ) {
return null;
}
$newNotification = $notifications->first();
$newNotification->ajax_call = false;
$newNotification->save();
$notification = DB::table('notifications')->leftjoin('users', 'users.id', 'notifications.current_user')->where('id', $noti->id)->first();
$pro_ulr = asset('/img/'.$notification->pic);
$arr = [
"username" => $notification->username,
"url" => $pro_ulr,
"name" => $notification->name,
"msg" => $notification->msg,
];
return response()->json($arr);
}
您遇到了一个问题,Table::first()
您需要致电get()
而不是first()
。另外,$new_noti->update();
可以代替$new_noti->save();
来使用。
答案 1 :(得分:0)