【问题标题】:Sync vote button with backend vote function与后台投票功能同步投票按钮
【发布时间】:2018-09-30 16:56:14
【问题描述】:

我有一个投票按钮,在我看来应该会立即改变颜色和计数。通过按钮触发的后端功能应该在后端处理,因此用户无法识别它。问题是,如果我使用 jquery 更改视图中按钮的颜色,如果用户非常快速地按下按钮,这将与后端功能不同步。所以我想知道如何处理这个?如果我使用 ajax 响应来做这件事需要很长时间......这不是一个好的用户体验。希望大家明白我的意思?

<a data-id="{{ $article->id }}" class="vote {{ Auth::check() && Auth::user()->votedFor($article) ? 'active' : '' }}"></a>

 <div class="points">{{ $article->votes->count() }}</div>

我想用来改变按钮颜色并在我的视图中计数的脚本

      $(document).on('click', '.vote', function() {
    var $counter = $(this).parent().find('.points');
    $(this).toggleClass('active');
    if($(this).hasClass('active')) {
      $counter.html(parseInt($counter.text(), 10) + 1);
    } else {
      $counter.html(parseInt($counter.text(), 10) - 1);
    }
    var $button = $(this);
    $button.addClass('vote-live');
    var id = $button.data('id');
    var token = $('meta[name="csrf-token"]').attr('content');
    $.ajax({

        type: 'POST',
        url: "{!! URL::to('article/vote/') !!}/" + id,
        dataType: 'JSON',
        data: {
            "_method": 'POST',
            "_token": token,
            "id": id,
        },
        success: function(data) {
            $counter.html(data.count);
            $button.removeClass('vote-live');
            // var color = data.voted ? 'transparent transparent #a53031 transparent' : 'transparent transparent #a53031 transparent';
            // $button.css('border-color', color);
            console.log('success');
            console.log(data);
        },
        error: function(xhr) {
            $button.removeClass('vote-live');
            if (xhr.status == 401) {
                window.location.href = "{!! URL::to('login') !!}";
            } else if (xhr.status == 403) {
                window.location.href = "{!! URL::to('email/verify') !!}";
            }
        },
    });
});

是这样,但不知道那是不是要走的路?看起来有点不专业,但我不知道它通常是怎么做的......

    $(this).toggleClass('active');
      if($(this).hasClass('active')) {
        $counter.html(1);
      } else {
        $counter.html(0);
      }

【问题讨论】:

  • 老兄,使用框架。
  • 你能推荐一个吗?
  • 我不知道你的整个结构,你的 web 应用程序要做什么,但对我来说,常青的选择总是 React。选择 react 意味着了解关注点的分离,这在开发中很重要,基本上可以帮助您不要失去理智。
  • 我不知道如何解决我的反应问题,从来没有使用过。我正在使用 laravel 5.7,它提供了开箱即用的 vue.js,但从未使用过它。

标签: jquery ajax laravel


【解决方案1】:

这里的解决方案是在服务尚未完成时禁用按钮。为此,您只需在用户单击按钮时添加类名.is-sending,这是 CSS:

.is-sending {
  pointer-events: none; // prevents the pointer event, so they cannot click
  cursor: default;
  opacity: 0.6; 
}

然后在success 中删除该类名。 我强烈建议你应该使用button 元素而不是a 元素,在这种情况下你可以使用disabled 属性而不是.is-sending 类名。

【讨论】:

  • 感谢一个非常好的主意,添加了上面的新脚本,它确实可以完美运行,但有时 jquery 计数错误。我的意思是,如果我点击非常快,会显示 3 而不是 2...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多