如何在AJAX调用中传递图片ID,实现图片点赞/点踩系统?
Got it, let's resolve this issue where you can't pass the correct image ID to your AJAX vote request. The core problem is that each like/dislike button needs to "know" which image it belongs to—we can solve this cleanly using HTML5 data-* attributes to store the image ID directly on the relevant elements.
Step 1: Add Image ID to Your HTML
First, update your Home view template to attach the image ID to a parent container (or directly to the like/dislike buttons). Using a parent container like imageContainer makes it resilient to small DOM changes later. I also fixed a tiny Laravel syntax typo (Session:token() → Session::token()) in your script.
Here's the modified loop:
@extends('layouts.app') @section('content') @foreach($images as $image) <div class='imageContainer' data-image-id="{{ $image->id }}"> <div class="stickyContainer blackGradient"> <h1 class='imageTitle'>{{$image->name}}</h1> <img class='uploadedImg' src='{{url("storage/uploads/images/".$image->file_name)}}' alt='Random image'/> <a class='specialA' href='{{url("image/".$image->id)}}'></a> <div class='votingContainer'> <a href='#'><div class='like'></div></a> <a href='#'><div class='dislike'></div></a> </div> </div> </div> @endforeach <script> var token = '{{ Session::token() }}'; var urlLike = '{{ route('like') }}'; </script> @endsection
Step 2: Retrieve the Image ID in Your JavaScript
Now, when a user clicks the like button, we'll traverse up the DOM to find the imageContainer and grab the stored image ID using jQuery's data() method. Update your JavaScript code like this:
$('.like').on('click', function(event){ event.preventDefault(); var isLike = event.target.previousElementSibling == null; // Get the image ID from the parent imageContainer var imageId = $(this).closest('.imageContainer').data('image-id'); console.log('Like status:', isLike, 'Image ID:', imageId); $.ajax({ method: 'POST', url: urlLike, data: { isLike: isLike, imageId: imageId, _token: token } }) .done(function(response) { // Optional: Handle success (e.g., update vote count on the page) console.log('Vote submitted successfully:', response); }) .fail(function(error) { // Optional: Handle errors gracefully console.error('Vote submission failed:', error); }); });
How This Works
- The
data-image-id="{{ $image->id }}"attribute stores the unique ID of each image directly on its container element—this is a standard HTML5 way to attach custom data to elements. $(this).closest('.imageContainer')finds the nearest parent element with theimageContainerclass, ensuring we get the correct ID for the image linked to the clicked button.data('image-id')retrieves the value from thedata-image-idattribute (jQuery automatically handles hyphen-to-camelCase conversion for data attributes).
Alternative: Attach ID Directly to Buttons
If you prefer to attach the ID directly to the like/dislike buttons, modify your HTML like this:
<div class='votingContainer'> <a href='#'><div class='like' data-image-id="{{ $image->id }}"></div></a> <a href='#'><div class='dislike' data-image-id="{{ $image->id }}"></div></a> </div>
Then retrieve it in JS with:
var imageId = $(this).data('image-id');
Either approach works—using the parent container is just more flexible if you ever need to access the image ID from other elements in the same container.
内容的提问来源于stack exchange,提问作者Onyx

