【发布时间】:2015-07-29 05:23:09
【问题描述】:
我需要实现 AJAX 及其正常工作。但是,我在将 ajax 应用于模型的每个实例时遇到问题。它只是应用于顶部对象并在同一页面上应用 ajax 调用。对于剩余的对象,当我单击链接时,它会将我定向到新页面并向我显示我不想要的 JSON 对象。
Views.py
def upvote(request, post_id):
if request.method == "POST":
p = get_object_or_404(Post, pk=post_id)
p.upvote += 1
p.save()
return JsonResponse({'count':p.upvote })
if request.method == "GET":
p = get_object_or_404(Post, pk=post_id)
p.upvote += 1
p.save()
data = {
'count' : p.upvote,
}
return JsonResponse({'count': p.upvote})
网址.py
url(r'^(?P<post_id>[0-9]+)/upvote/$', views.upvote, name='upvote-detail'),
Views.html
<script>
$(function(){
$('#up_vote').click(function(e) {
e.preventDefault();
window.alert("hello");
console.log("hello");
$.ajax({
url: $(this).attr('href'),
type :'get' ,
success : function (data){
// alert('success');
$('#upvote_count').html(data.count);
},
failure : function (data){
alert('failure') ;
}
}) ; // ajax call
}); // upvote link call
</script>
<div id="columns">
{% for post in object_list %}
<div class="pin">
<a href="/posts/{{ post.id }}/">
<img src= "/static/media/{{post.image}}" />
</a>
<p>
{{post.description}}
(<a href="{% url "post-edit" pk=post.id %}">edit</a>)
</p>
<div style="float:left">
<a href='{% url 'upvote-detail' post.id %}' id='up_vote'>Up vote </a>
<span id='upvote_count'> {{ post.upvote }} </span>
</div>
<div style="float:right">
<a href='{% url 'downvote-detail' post.id %}' id='down_vote'> Down vote </a>
<span id='downvote_count'>{{post.downvote}}</span>
</div>
</div>
{% endfor %}
</div>
这是我所有的文件。目前 AJAX 调用运行良好。它只是应用于 LOOP 中对象的顶部(第一个)。对于剩余对象,当我单击链接时,它会将我呈现到新页面。有人可以识别问题吗?谢谢,
【问题讨论】:
标签: jquery python ajax django django-models