【发布时间】:2021-12-23 06:29:30
【问题描述】:
我有一个在页面上添加喜欢的功能
blade.php
<a href="/article/{{ $article->id }}?type=heart" class="comments-sub-header__item like-button">
<div class="comments-sub-header__item-icon-count">
{{ $article->like_heart }}
</div>
<a href="/article/{{ $article->id }}?type=finger" class="comments-sub-header__item like-button">
<div class="comments-sub-header__item-icon-count">
{{ $article->like_finger }}
</div>
js
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
});
$('.like-button').on('click', function(event) {
event.preventDefault();
let href = $(this).attr('href');
$.ajax({
url: href,
type: 'POST',
success: function() {
window.location.reload();
},
});
});
});
但是当我点赞更新数据时,我使用window.location.reload();重新加载页面
可以在不重新加载页面的情况下以某种方式完成吗?
这就是添加喜欢的实现方式,它们被添加到 cookie 中并存储 24 小时
网络路由
Route::post('article/{id}', 'App\Http\Controllers\ArticleController@postLike');
文章控制器
public function postLike($id, Request $request) {
$article = Article::find($id);
if(!$article){
return abort(404);
}
$type = $request->input('type');
if ($article->hasLikedToday($type)) {
return response()
->json([
'message' => 'You have already liked the Article '.$article->id.' with '.$type.'.',
]);
}
$cookie = $article->setLikeCookie($type);
$article->increment("like_{$type}");
return response()
->json([
'message' => 'Liked the Article '.$article->id.' with '.$type.'.',
'cookie_json' => $cookie->getValue(),
])
->withCookie($cookie);
}
文章模型
public function hasLikedToday(string $type)
{
$articleLikesJson = Cookie::get('article_likes', '{}');
$articleLikes = json_decode($articleLikesJson, true);
if (!array_key_exists($this->id, $articleLikes)) {
return false;
}
if (!array_key_exists($type, $articleLikes[$this->id])) {
return false;
}
$likeDatetime = Carbon::createFromFormat('Y-m-d H:i:s', $articleLikes[$this->id][$type]);
return ! $likeDatetime->addDay()->lt(now());
}
public function setLikeCookie(string $type)
{
$articleLikesJson = Cookie::get('article_likes', '[]');
$articleLikes = json_decode($articleLikesJson, true);
$articleLikes[$this->id][$type] = now()->format('Y-m-d H:i:s');
$articleLikesJson = json_encode($articleLikes);
return cookie()->forever('article_likes', $articleLikesJson);
}
【问题讨论】:
-
只需添加一个类来为ajax成功方法中的like按钮着色。您还可以从 POST 响应中返回点赞数,并通过成功方法更新标记中的数据。
-
@TaimurSaeed 我不擅长ajax和js,也不太懂怎么做,求详细解答
-
请描述一下你想在 ajax 成功时更新什么样的数据
-
@TaimurSaeed 使用
comments-sub-header__item-icon-count类添加到帖子中的 php.blade 中的所有内容 -
@OzanKurt 嗨,已添加到帖子中
标签: javascript jquery ajax laravel