【问题标题】:Refresh data without reloading the page刷新数据而不重新加载页面
【发布时间】: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


【解决方案1】:

假设这些 DIV 中包含红心数,如果目标页面的响应是新的红心数,那么:

 success: function(data) {
    targetElement.find(".comments-sub-header__item-icon-count").html(data)
 }

如果您想在当前号码上加上 +1 而不管服务器响应如何:

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

脚注:由于 ajax 请求嵌套在 click 函数中,所以我的代码中的 targetElement 是被点击的元素。您可以通过不同的方式获得它,例如

$('.like-button').on('click', function(event) {
     var targetElement=$(this);
     ....
}

【讨论】:

  • 很遗憾,在我刷新页面之前什么都没有发生
  • 应该有一些其他错误阻止该功能正常工作。请检查控制台查找错误发生的位置。@chu
  • 没有错误,我检查了一切,只是数据没有更新
  • 好的。我发现您将 ajax 请求嵌套在 click 函数中。所以我根据脚注中描述的targetElement更新了答案。@chu
  • 在我刷新页面之前没有任何变化
【解决方案2】:
$(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)
      },
    });
  });
});

【讨论】:

  • 试过了,在我刷新页面之前什么都没有发生
【解决方案3】:

这应该适合你

$(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);
      },
    });
  });
});

【讨论】:

  • 得到错误Uncaught ReferenceError: parsetInt is not defined
  • 抱歉parseInt有错别字
  • 没有错误,但是不重新加载页面没有更新
  • 你可以在success方法中附加一个调试器来看看为什么会这样。如果不查看可行的解决方案,很难提出解决方案
  • 如何做到这一点?
【解决方案4】:

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

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)
    },
});

【讨论】:

  • 不幸的是没有帮助(没有重新启动数据不会更新
猜你喜欢
  • 2021-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 2012-03-06
  • 1970-01-01
  • 2019-05-28
相关资源
最近更新 更多