我正在尝试使laravel最喜欢的系统(https://github.com/ChristianKuri/laravel-favorite)正常工作。我已经按照自述文件中的说明安装了它。
当我单击“赞”按钮时,它返回成功,但是该函数似乎无法执行。
我已经尝试过像这样的ajax:
$('.btn-heart').on('click', function(){
$.ajax({
type: "GET",
url: 'http://localhost/view/<?php echo $post->post_id; ?>',
data: {post_id: '<?php echo $post->post_id; ?>'},
success: function(data){
alert('working')
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
})
或类似的
$('.btn-heart').on('click', function(){
$.ajax({
type: "GET",
url: 'http://localhost/view/',
data: {post_id: '<?php echo $post->post_id; ?>'},
success: function(data){
alert('working')
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
})
我必须清楚,post_id是我的posts表中唯一的post_id。
我的view.blade.php:
<div class="card-body no-padding">
<div class="card-image-wrapper">
<div class="img-card-img">
<img src="{{ $post->post_url }}" class="card-image"/>
</div>
<div class="overlay-img"></div>
</div>
<div class="card-padding-user">
<div class="float-left">
<button class="btn btn-default btn-heart"><i class="far fa-heart icon-middle icon-thre"></i><i class="fa fa-heart icon-middle icon-non"></i> <span class="align-middle ml-2">0 Likes</span></button>
</div>
<div class="clearfix"></div>
</div>
</div>
我的web.php:
Route::get('/view/{post_id}',"PostController@like");
我的PostController:
public function like($post_id)
{
$post = Post::where('post_id', $post_id)->first();
$user = Auth::user();
$user->toggleFavorite($post);
return response()->json(['status' => 1]);
}
我的用户模型:
use Notifiable;
use Favoriteability;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'avatar', 'full_name'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function posts() {
return $this->hasMany(Post::class, 'creator','name');
}
我的帖子模型:
use Favoriteable;
protected $fillable = [
'creator', 'post_url', 'game', 'likes', 'created_at'
];
public function user() {
return $this->belongsTo(User::class);
}
该函数根本无法正常工作,没有任何东西插入到收藏夹表中。
答案 0 :(得分:0)
所以我设法使其正常工作。
代替使用GET方法,您需要使用POST方法并包含CSRF令牌
$('.button-like').on('click', function(){
$.ajax({
type: "post",
url: '/view/<?php echo $post->post_id; ?>',
data: {postid: '<?php echo $post->post_id; ?>', _token: '{{ csrf_token() }}'}
});
})