我在幾天內都在與這個問題作斗爭,但找不到適合我的情況的解決方案。我正在嘗試在不重繪 頁面的情況下制作喜歡系統。在喜歡和不喜歡的同步模式下作業正常,但是當我嘗試添加 AJAX 時,我得到 405,并且只有最后一條評論可以單擊,我理解 Ajax 不理解 django url 的問題或 pk 喜歡我的變體 {% url 'store:like' comment.pk %} ,但如何解決?
模板中有這一部分:
{% for comment in comments %}
<h6 class="card-header">
{{ comment.author }}<small> добавлен {{ comment.created_at|date:'M d, Y H:i' }} </small>
</h6>
<div class="card-body">
<h4>{{ comment }}</h4>
<form id="like-{{comment.pk}}" method="POST" action="{% url 'store:add_like' comment.pk %}">
{% csrf_token %}
<button style="background-color: transparent; border: none; box-shadow: none;" type="submit">
<a class="btn btn-success" id="like-count-{{comment.pk}}"> Likes {{ comment.likes.all.count }}</a>
</button>
</form>
</div>
{% empty %}
<p>Для данного товара ещё нет комментариев.</p>
{% endfor %}
我在同一個模板中呼叫 ajax:
<script type="text/javascript">
$(document).ready(function(){
$('[id^="like-"]').submit(function(e){
e.preventDefault();
var endpoint = $(this).attr('action');
var serializedData = $(this).serializeArray();
$.ajax({
type: 'POST',
url: endpoint,
data: serializedData,
success: function(response) {
$( "#like-count-" response["id"].toString()).text("Likes " response["like_count"]);
},
error: function(rs, e) {
alert(rs.responseText);
}
});
})
這部分來自網址:
path('products/<int:pk>/like/', addlike, name='like'),
查看喜歡:
@api_view(['POST'])
def addlike(request, pk, *args, **kwargs):
is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
if request.method == 'POST' and is_ajax:
post = Comment.objects.get(pk=pk)
is_dislike = False
for dislike in post.dislikes.all():
if dislike == request.user:
is_dislike = True
break
if is_dislike:
post.dislikes.remove(request.user)
is_like = False
for like in post.likes.all():
if like == request.user:
is_like = True
break
if not is_like:
post.likes.add(request.user)
if is_like:
post.likes.remove(request.user)
all_post_likes = post.total_likes() (function from models)
return JsonResponse({"success": True, "like_count": all_post_likes, "id": pk}, status=200)
else:
return JsonResponse({"success": False}, status=400)
如何強制 AJAX 呼叫我需要的 pk?(最后我找到了解決方案,更新了代碼的最終版本)
uj5u.com熱心網友回復:
卸下data-url?并設定action,因為當你點擊提交按鈕,默認情況下該屬性POST請求將被發送到當前的網址,你會收到405狀態碼,但如果你設定action這個POST請求將會被發送到like網址:
<form id="like" method="POST" action="{% url 'store:like' comment.pk %}">
{% csrf_token %}
<input type="hidden" value="{{comment.pk}}" name="id">
<input type="hidden" name="next" value="{{ request.path }}">
<button style="background-color: transparent; border: none; box-shadow: none;" type="submit">
<a class="btn btn-success" id="like"> Likes {{ comment.likes.all.count }}</a>
</button>
</form>
在js中你可以得到這樣的URL
var endpoint = $(this).attr('action');
更新
所有表單都具有相同的“ID”,因此只執行第一個表單,其余表單不由 Ajax 管理,要解決此問題,您可以ID對表單進行不同的處理(此條件也適用于a標簽):
<form id="like-{{comment.pk}}" method="POST" action="{% url 'store:like' comment.pk %}">
{% csrf_token %}
........
.....
<a class="btn btn-success" id="likes-count-{{comment.pk}}"> Likes {{ comment.likes.all.count }}</a>
您可以通過這種方式接收事件并更新喜歡的數量。
$(document).ready(function(){
$('[id^="like-"]').submit(function(e){
e.preventDefault();
var endpoint = $(this).attr('action');
var serializedData = $(this).serializeArray();
$.ajax({
url: endpoint,
method: "POST",
data: serializedData,
success: function(response){
$("#likes-count-" serializedData[1].value).text("Likes " response["like_count"]);
}
});
})
});
在視圖中,您應該回傳新的點贊數:
return JsonResponse({"success": True, "like_count": new_like_count}, status=200)
在成功函式中,您可以通過 獲取新數字response,現在我們更改a標簽的文本值以更改點贊數。
^=意思是:選擇具有指定屬性的元素,其值恰好以給定字串開頭。屬性StartsWith1
uj5u.com熱心網友回復:
我認為您應該將 csrf_token 與 ajax 請求一起發送
headers: { "X-CSRFToken": token }到您的 ajax 請求中,“token 是 csrf_token”或將 @csrf_exempt 裝飾器添加到您的函式中,但它會使您的視圖不安全地抵御 CSRF 攻擊。
你可以在這里找到更多資訊https://docs.djangoproject.com/en/4.0/ref/csrf/
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/407850.html
標籤:
