如何在Laravel中使用jQuery Ajax创建Like/Dislike功能?

xuo3flqw  于 2023-11-20  发布在  jQuery
关注(0)|答案(1)|浏览(106)

我在Laravel中使用jQuery Ajax创建了一个Like/Dislike功能。功能上,Like/Dislike动作正常运行。问题是,当我在property-id = 6上单击Like时,添加到喜欢的类中的是property-id = 5。如果我在property-id = 6上单击Like,则添加到喜欢的类中的是property-id = 6。应该是,如果我点击取消属性id = 6的行,那么属性id = 6上的喜欢的类必须被删除。如何解决这个问题?下面,我包括我创建的代码。

刀锋

<div class="property-listing">
    <div class="row g-2">
        @foreach ($properties as $property)
        <div class="col-lg-6 col-12 mb-3">
            <div class="card property-item shadow-sm p-2 pb-0 h-100">
                <div class="position-absolute top-0 start-0 z-index-1 m-4">
                    <div class="badge text-bg-light">
                        From ${{ $property->monthly_price }}/month
                    </div>
                </div>
                <div class="position-absolute top-0 end-0 z-index-1 m-4">
                    <button class="btn favorite-btn rounded-circle {{ $property->isLiked() ? 'liked' : '' }}" aria-label="like" type="button" data-property-id="{{ $property->id }}" id="like-btn">
                    <i class="fa-solid fa-heart fs-3"></i>
                    </button>
                </div>
                <div class="rounded-2 overflow-hidden">
                    <div class="property-galleries mb-0">
                        @foreach ($property->getMedia('property images') as $media)
                        <div><img data-src="{{ $media->getFullUrl() }}" class="lazy" alt="{{ $property->title }}"></div>
                        @endforeach
                    </div>
                </div>
                <div class="position-relative">
                    <div class="card-body px-1 pb-0">
                        <h2 class="card-title fw-bold">
                            <a href="{{ route('front.property-detail', $property->slug) }}">
                            <span class="fw-bold">
                            {{ $property->title }}
                            </span>
                            </a>
                        </h2>
                        <div class="meta">
                            <ul>
                                <li>
                                    {{ $property->district->name }}
                                </li>
                                <li>
                                    {{ $property->specification }}
                                </li>
                                <li>
                                    {{ $property->size }} Sq Ft
                                </li>
                            </ul>
                        </div>
                    </div>
                    <div class="card-footer border-0 bg-transparent px-1 pt-2 d-flex mx-auto">
                        <div class="d-flex flex-column">
                            <span class="text-muted small">
                            Starting at
                            </span>
                            <span class="fw-normal small">
                            ${{ $property->nightly_price }}/night
                            </span>
                        </div>
                        <a href="{{ route('front.property-detail',$property->slug) }}" class="btn btn-sm check-btn mb-0 mt-3 ms-auto stretched-link">Check Availability</a>    
                    </div>
                </div>
            </div>
        </div>
        @endforeach
    </div>
</div>

字符串

** AJAX **

$(document).on('click', '#like-btn', function(e) {
    e.preventDefault();
    var id = $(this).data('property-id');
    var url = "{{ route('like', ':id') }}";
    url = url.replace(':id', id);
    $.ajax({
        url: url,
        method: 'POST',
        data: {
            _token: '{{ csrf_token() }}'
        },
        success: function(response) {
            if (response.message == 'liked') {
                //add class liked to #like-btn button with data-id = id
                $('#like-btn').addClass('liked');
            }
    
            if (response.message == 'unliked') {
                //remove class liked
                $('#like-btn').removeClass('liked');
            }
        }
    });
});

控制器

public function like(Property $property)
{
    try {
        if ($property->isLiked()) {
            $property->removeLike();
            return response()->json(['message' => 'unliked'], 200);
        }

        $property->likes()->create([
            'user_id' => auth()->id(),
            'ip' => request()->ip(),
            'user_agent' => request()->userAgent(),
        ]);
        
        return response()->json(['message' => 'liked'], 200);

    } catch (\Exception $e) {
        return response()->json(['message' => $e->getMessage()], 500);
    }
}

wmvff8tz

wmvff8tz1#

解决了。我像这样修改了Ajax脚本。

** AJAX **

$(document).on('click', '.favorite-btn', function(e) {
    e.preventDefault();
    var id = $(this).data('property-id');
    var url = "{{ route('like', ':id') }}";
    url = url.replace(':id', id);
    $.ajax({
        url: url,
        method: 'POST',
        data: {
            _token: '{{ csrf_token() }}'
        },
        success: function(response) {
            if (response.message == 'liked') {
                $('.favorite-btn[data-property-id=' + id + ']').addClass('liked');
            }
    
            if (response.message == 'unliked') {
                $('.favorite-btn[data-property-id=' + id + ']').removeClass('liked');
            }
        },
        error: function(error) {
            if (error.status == 401) {
                window.location.href = "{{ route('login') }}";
            }
            console.log(error);
        }
    });
});

字符串

相关问题