繁体   English   中英

刷新数据而不重新加载页面

[英]Refresh data without reloading the page

我有一个在页面上添加喜欢的功能

刀片.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();重新加载页面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);
    }
$(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(response) {
        $(this).parent(".comments-sub-header__item-icon-count").html(
parseInt($(this).parent(".comments-sub-header__item-icon-count").html()) + 1
)
// or return like or heart count from server
$(this).parent(".comments-sub-header__item-icon-count").html(response)
      },
    });
  });
});

这应该适合你

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

  $(".like-button").on("click", function (event) {
    event.preventDefault();

    const likeBtn = $(this);

    $.ajax({
      url: likeBtn.attr("href"),
      type: "POST",
      success: function () {
        let currentCount = likeBtn.next().text();
        likeBtn.next().text(parseInt(currentCount) + 1);
      },
    });
  });
});

假设这些 DIV 持有红心数,如果目标页面的响应是新的红心数,则:

 success: function(data) {
    $(this).next(".comments-sub-header__item-icon-count").html(data)
 }

在别处,如果您想将 +1 添加到当前号码,而不管服务器响应如何:

 success: function() {
    var current= parseInt($(this).next(".comments-sub-header__item-icon-count").html());
    $(this).next(".comments-sub-header__item-icon-count").html(current+1)
 }

您可以简单地将新计数添加到控制器的响应中。

return response()
    ->json([
        'message' => 'Liked the Article '.$article->id.' with '.$type.'.',
        'cookie_json' => $cookie->getValue(),
        'new_count' => $article->{"like_{$type}"},
    ])
    ->withCookie($cookie);

现在,您可以将更新后的计数用作数据库中的new_count

$.ajax({
    url: href,
    type: 'POST',
    success: function (response) {
        $(this).next().text(response.new_count)
    },
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM