gpt4 book ai didi

ajax - 在跟随 Laravel 上构建 AJAX 按钮

转载 作者:行者123 更新时间:2023-12-04 07:19:18 24 4
gpt4 key购买 nike

我的 Blade View
我正在实时更新关注按钮,所以我注意到如果我点击取消关注它会自动更新以关注,但是当我点击关注时它什么也不做,直到我手动刷新页面

<button data-id="{{ $user->id }}" class="w-1/2 px-3 py-2 text-base text-white border rounded-lg action-follow bg-blue-lite hover:bg-blue"> <strong>
@if (auth()->user()->isFollowing($user))
UnFollow
@else
Follow
@endif
</strong>
</button>
$(document).ready(function() {

$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

$('.action-follow').click(function(){
var user_id = $(this).data('id');
var cObj = $(this);
var c = $(this).parent("div").find(".tl-follower").text();

$.ajax({
type:'POST',
url:'/profile/follow',
data:{user_id:user_id},
success:function(data){
console.log(data.success);
if(jQuery.isEmptyObject(data.data)){
cObj.find("strong").text("Follow");
cObj.parent("div").find(".tl-follower").text(parseInt(c)-1);
}else{
cObj.find("strong").text("UnFollow");
cObj.parent("div").find(".tl-follower").text(parseInt(c)+1);
}
}
});
});

});

我的 Controller
public function follwUserRequest(Request $request){

$user = User::find($request->user_id);
$response = auth()->user()->toggleFollow($user);

return response()->json(['success'=>$response]);
}

最佳答案

试试这个:

  $user = User::find($request->user_id);
$response = auth()->user()->toggleFollow($user);
$status = auth()->user()->isFollowing($user);

return response()->json([ 'success' => $response, 'is_following' => $status ]);
<button data-id="{{ $user->id }}" id="mybutton{{ $user->id }}"  class="w-1/2 px-3 py-2 text-base text-white border rounded-lg action-follow bg-blue-lite hover:bg-blue">
<strong>
@if (auth()->user()->isFollowing($user))
UnFollow
@else
Follow
@endif
</strong>
</button>
$.ajax({
type:'POST',
url:'/profile/follow',
data:{user_id:user_id},
success:function(data){
console.log(data);
if(data.is_following == true){
cObj.find("strong").text("UnFollow");
cObj.parent("div").find(".tl-follower").text(parseInt(c)+1);
}else{
cObj.find("strong").text("Follow");
cObj.parent("div").find(".tl-follower").text(parseInt(c)-1);
}
}
});

关于ajax - 在跟随 Laravel 上构建 AJAX 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68602924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com