繁体   English   中英

jQuery和验证无法在laravel5中单击

[英]jquery and validate does not work on click in laravel5

首先,我为英语不好对不起。 我现在使用laravel(版本5.4.24)为网站帖子创建投票按钮。

如果我仅在代码中使用<button> ,则在单击屏幕上的“投票”按钮时将无法使用。 因此,作为替代,我使用表单传递了值,但此方法似乎在验证中未正确传递json的值。

该问题发生在“这里”部分,如果我删除ArticleController.php的“这里”部分并单击按钮,则它没有向上或向下的值。 如果删除“ part”并运行,laravel将显示以下错误:

SQLSTATE [42S22]: Column not found: 1054 Unknown column '' in 'field list' (SQL: SELECT sum (` `) as aggregate from` votes` where `votes`.`article_id` = 107 and` votes`. `article_id` is not null)

我一直在寻找一种方法,但没有找到答案。

谢谢您的帮助。 谢谢。

show.blade.php

//<form ...> </ form> is code that was not in the example, but if I click on 
<button> without it, there is no response on the screen.(No redirects)
<div class="action__article">
<form action="{{ route('videos.vote', $article->id) }}" method="post">
@if ($currentUser)
{!! csrf_field() !!}
<button class="btn__vote__article" data-vote="up" title="{{ trans('forum.comments.like') }}" {{ $voted }}>
<i class="fa fa-heart"></i>
<span>{{ $article->up_count }}</span>
</button>
@endif
</form>
</div>

* index.blade.php

@section('script')
@parent
<script type="text/javascript" charset="utf-8">
$.ajaxSetup({
  headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('vote')
 }
});

$('.btn__vote__article').on('click', function(e) {
  var self = $(this),
    articleId = $article['id'];
  $.ajax({
    type: 'POST',
    url: '/video/' + articleId + '/votes',
    data: {
      vote: self.data('vote')
    }
  }).then(function (data) {
    self.find('span').html(data.value).fadeIn();
    self.attr('disabled', 'disabled');
    self.siblings().attr('disabled', 'disabled');
  });
});
</script>
@endsection

* ArticleController.php

public function vote(Request $request, \App\Article $article)
{
   //"here" - The value received from the form will not pass here and will be redirected to the previous page.
    $this->validate($request, [
        'vote' => 'required|in:up,down',
    ]);

    if ($article->votes()->whereUserId($request->user()->id)->exists()) {
        return response()->json(['error' => 'already_voted'], 409);
    }

    $up = $request->input('vote') == 'up' ? true : false;

    $article->votes()->create([
        'user_id'  => $request->user()->id,
        'up'       => $up,
        'down'     => ! $up,
        'voted_at' => \Carbon\Carbon::now()->toDateTimeString(),
    ]);

    return response()->json([
        'voted' => $request->input('vote'),
        'value' => $article->votes()->sum($request->input('vote')),
    ], 201, [], JSON_PRETTY_PRINT);
}

$ article = new App \\ Article; $ request =新的App \\ Http \\ Requests \\ ArticlesRequest;

*模型

class Vote extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id',
        'up',
        'down',
        'voted_at',
    ];

    /**
     * The attributes that should be visible in arrays.
     *
     * @var array
     */
    protected $visible = [
        'user_id',
        'up',
        'down',
    ];

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = [
        'voted_at',
    ];

    /* Relationships */

    public function articles()
    {
        return $this->belongsTo(Article::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /* Mutators */

    public function setUpAttribute($value)
    {
        $this->attributes['up'] = $value ? 1 : null;
    }

    public function setDownAttribute($value)
    {
        $this->attributes['down'] = $value ? 1 : null;
    }
}

*数据库

MariaDB [mmdance]> desc votes
    -> ;
+------------+------------------+------+-----+-------------------+----------------------------               -+
| Field      | Type             | Null | Key | Default           | Extra                                      |
+------------+------------------+------+-----+-------------------+----------------------------               -+
| id         | int(10) unsigned | NO   | PRI | NULL              | auto_increment                             |
| user_id    | int(10) unsigned | NO   | MUL | NULL              |                                            |
| article_id | int(10) unsigned | NO   | MUL | NULL              |                                            |
| up         | tinyint(4)       | YES  |     | NULL              |                                            |
| down       | tinyint(4)       | YES  |     | NULL              |                                            |
| voted_at   | timestamp        | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP                |
+------------+------------------+------+-----+-------------------+----------------------------               -+
6 rows in set (0.00 sec)

问题出在这里,您需要在此处传递$request实例,在此处您需要传递字段名称

return response()->json([
        'voted' => $request->input('vote'),
        'value' => $article->votes()->sum('vote'),
    ], 201, [], JSON_PRETTY_PRINT);
}

单击此处查看sum()工作方式

这是因为您可能没有数据库表中的字段,或者您没有在模型中添加任何字段,如下所示。

protected $fillable = [
    'user_id',
    'up',
    'down',
    'voted_at',
];

暂无
暂无

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

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