在Django中使用AJAX制作Like按钮涉及前端和后端的交互。以下是实现这一功能的步骤:
<!-- templates/your_template.html -->
<button id="like-button" data-post-id="{{ post.id }}">Like</button>
<div id="like-count">{{ post.like_count }}</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('#like-button').click(function() {
var postId = $(this).data('post-id');
$.ajax({
url: '/like_post/', // 后端处理URL
type: 'POST',
data: {
'post_id': postId,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function(response) {
$('#like-count').text(response.like_count);
$('#like-button').text(response.button_text);
},
error: function(xhr, status, error) {
console.error("Error: " + error);
}
});
});
});
</script>
# views.py
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Post
@csrf_exempt
def like_post(request):
if request.method == 'POST':
post_id = request.POST.get('post_id')
post = Post.objects.get(id=post_id)
post.like_count += 1
post.save()
return JsonResponse({
'like_count': post.like_count,
'button_text': 'Liked' if post.like_count > 0 else 'Like'
})
return JsonResponse({'error': 'Invalid request'}, status=400)
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('like_post/', views.like_post, name='like_post'),
]
通过以上步骤,你可以在Django中实现一个使用AJAX的Like按钮。
1 将文件保存到服务器本地
upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
领取专属 10元无门槛券
手把手带您无忧上云