首页 > 解决方案 > 如何获取 data-id Laravel 的值

问题描述

我正在尝试获取正在查看的数据 ID 的值。我正在尝试获取“data-reviewid”。

这是我的看法。

Show.blade.php

<div class="container">
        <div class="row">
            <div class="col-md-6" id="user-reviews">
            <h3>Recent comments</h3>
                @forelse($product->reviews as $review)
                <div class="comment mt-5 border border-dark pl-3 pt-3 pb-3 mb-3 rounded reviewid" data-reviewid="{{ $review->id }}">
                    <div class="title">
                        <h4>{{ $review->headline }}</h4>
                    </div>
                    <div class="user-rating">
                        <star-rating class="pr-3" :star-size="20" :read-only="true" :show-rating="false" :rating="{{ $review->rating }}"></star-rating>
                    </div>
                    <div class="body-text pt-3 pr-5">
                        <p style="text-align:justify"><strong>{{ $review->description }}</strong></p>
                    </div>
                    <div class="body-text pt-3">
                        <h6>
                            <a href="#" class="btn btn-xs btn-warning like">Like</a>
                            <a href="#" class="btn btn-xs btn-danger like">Dislike</a>
                        </h6>
                    </div>
                    <div class="author pt-2">
                        <h6 class="text-muted">{{ $review->user_name }},  {{ date('d-m-Y', strtotime( $review->created_at )) }}</h6>
                    </div>
                </div>
                @empty
                <h6>There are not reviews for this product</h6>
                @endforelse
            </div>
        </div>
    </div>

这是我试图获取它的 JS 文件,但每次我在 reviewId 中执行 console.log 时,它都会返回我,因为它是未定义的。

应用程序.js

$('.like').on('click', function(event) {
    event.preventDefault();
    reviewId = event.target.parentNode.parentNode.dataset['reviewid'];
    var isLike = event.target.previousElementSibling == null;

    $.ajax({
        method: 'POST',
        url: urlLike,
        data: {isLike: isLike, reviewId: reviewId, _token:token},
        success: function( data ) {
        },
        error: function(xhr, status, error) {
           // check status && error
        },
        dataType: 'text'
    })
    console.log(reviewId)
});

现在,我可以获取数据集的数据,但现在的问题是,当我执行 POST 请求时,它会抛出下一个错误:

POST http://localhost:8000/like 500 (Internal Server Error)
send @ app.js:12639
ajax @ app.js:12245
(anonymous) @ like.js:6
dispatch @ app.js:8222
elemData.handle @ app.js:8030

我怎样才能更好地看到这个错误?

标签: jqueryajaxlaravellaravel-5

解决方案


由于使用 jQuery 已经很简单closest()data()

$('.like').on('click', function(event) {
    event.preventDefault();
    var revId = $(this).closest('.comment').data('reviewid')
   ....

推荐阅读