如何不使用jQuery通过Ajax发送整数?Django视图接收数据异常求助
Hey there! Let's troubleshoot why your petadid integer isn't reaching your Django petadlikeview—it's super common to hit these snags when starting out with Ajax and Django, so let's break it down step by step.
1. Fix the $(this) Context in Your JavaScript
The biggest red flag here is how you're trying to grab petadid:
var petadid = $(this).attr("data-petadid");
In your current code, this refers to the document object (since you're inside the $(document).ready() callback), not the #likes element you're targeting. That means you're trying to get a data-petadid attribute from the document, which doesn't exist—so petadid ends up as undefined, and nothing gets sent to your view.
Here's how to fix this:
Option 1: Grab the attribute directly from your element
<script> $(document).ready(function() { $.ajaxSetup({cache:false}); var element = document.getElementById("likes"); // Use the element variable instead of $(this) var petadid = $(element).attr("data-petadid"); element.addEventListener("click", function(){ // Your Ajax request logic here }); }); </script>
Option 2 (Better for interactivity): Get petadid inside the click handler
This is cleaner because this will correctly refer to the clicked #likes element when the event fires:
<script> $(document).ready(function() { $.ajaxSetup({cache:false}); $("#likes").on("click", function() { // Now $(this) points to the #likes element! var petadid = $(this).attr("data-petadid"); // Send the Ajax request $.ajax({ url: "/your-url-path/petadlikeview/", // Replace with your actual URL type: "POST", data: { 'petadid': petadid, // Make sure this key matches what your view expects // Critical: Include Django's CSRF token to avoid 403 errors 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, success: function(response) { // Handle success (e.g., update the UI) console.log("Success!", response); }, error: function(xhr) { // Debug errors console.log("Error:", xhr.responseText); } }); }); }); </script>
2. Double-Check Your Django View
Make sure your view is correctly pulling the petadid from the POST data. Using .get() is safer than direct indexing because it won't throw an error if the key is missing:
from django.http import JsonResponse def petadlikeview(request): if request.method == 'POST': # Match the key name exactly to what you sent in Ajax (case-sensitive!) petadid = request.POST.get('petadid') print("Received petadid:", petadid) # This should now show the correct value # Add your like logic here return JsonResponse({'status': 'success'}) else: # Reject non-POST requests return JsonResponse({'status': 'error', 'message': 'Only POST requests allowed'})
Also, confirm your URL pattern is correctly mapped in urls.py:
from django.urls import path from . import views urlpatterns = [ # Other URLs... path('petadlike/', views.petadlikeview, name='petadlikeview'), ]
3. Debugging Tips to Verify
- Open your browser's DevTools (F12) → go to the Network tab. When you click the
#likeselement, look for your Ajax request. Check the Request Payload section—you should seepetadidwith its value here. If not, the issue is still in your JS. - If the payload has
petadidbut your view printsNone, double-check that the key name is identical (e.g.,petadidvspetadId—case matters!). - Check the Console tab in DevTools for any JS errors (like "element not found" or "attribute undefined").
内容的提问来源于stack exchange,提问作者Zadid Hasan

