我正在尝试为我的Django项目(Python的框架)创建一个类似Ajax的按钮。基本上,我正在做的是在Ajax调用成功时对 index.html 进行部分更新。它第一次工作正常,但是当第二次点击具有相同id的按钮时,它将重新加载整个页面,这不是我所期望的。谁能教我如何防止这种情况发生?
我不确定Python方面是否与此有任何关系,但我还是会粘贴一些代码。谢谢。
main.js
$('button').on('click', function(event){
event.preventDefault();
var element = $(this);
$.ajax({
url : element.attr("data-id") + '/like/',
type : 'POST',
data : { card_id : element.attr("data-id")},
success : function(response){
console.log(response);
$('#like-area-' + element.attr("data-id")).load(document.URL + ' #like-area-' + element.attr("data-id"));
}
})
})
// using jQuery
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
模板/ index.html中
{% for card in cards %}
......
<section id="like-area-{{ card.id }}">
<!-- currently testing if ajax works properly with this button-->
<form method="post">
{% csrf_token %}
<button data-id="{{ card.id }}" class="btn btn-default">いいね</button>
</form>
<!-- ultimately I'd like to fire up ajax through this anchor tag -->
<a id="like-button-{{ card.id }}" href="{% url 'like-post' card.id %}"><span class="glyphicon glyphicon-heart
{% for your_like in your_likes %}
{% if card == your_like.liked_post %}
red no-border
{% endif %}
{% endfor %}
"></span></a>
</section>
.....
{% endfor %}
views.py
def like_post(request, card_id):
if Like.objects.filter(liker=request.user, liked_post = card_id).exists():
existing_like = Like.objects.get(liker=request.user, liked_post = card_id)
existing_like.delete()
likes = Like.objects.all()
is_liked = 0
# return HttpResponse(likes)
return HttpResponse(is_liked) #not really using this yet
else:
card = Card.objects.get(id=card_id)
new_like = Like(liker=request.user, liked_post = card)
new_like.save()
# likes = Like.objects.all()
likes = Like.objects.all()
is_liked = 1
return HttpResponse(is_liked) #not really using this yet
urls.py
url(r'^(?P<card_id>[0-9]+)/like/$', views.like_post, name='like-post'),
答案 0 :(得分:0)
我刚看了你的请求:ajaxcầnot click 2次(需要重装或自动重装页面)
〜&GT;为ajax创建一个var并将其中止。
var ajaxcall1
def ...
if (ajaxcall1)
ajaxcall1.abort();
# some more code
你可以尝试一下,我只是觉得你没有检查状态。如果没有,我会检查更多详细信息