有我的Ajax请求发生在Django

有我的Ajax请求发生在Django

问题描述:

文本我有跟随按钮,它的工作原理是使用Ajax {{ total_followers }}作品以及通过增加或在点击减小之前刷新页面,但遵循取消关注按钮时才改变我刷新整个页面是什么,我不想有我的Ajax请求发生在Django

我的观点

@ajax_required 
@require_POST 
@login_required 
def user_follow(request): 
    user_id = request.POST.get('id') 
    action = request.POST.get('action') 
    if user_id and action: 
     try: 
      user = User.objects.get(id=user_id) 
      if action == 'follow': 
       Contact.objects.get_or_create(user_from=request.user,user_to=user) 
      else: 
       Contact.objects.filter(user_from=request.user,user_to=user).delete() 
      return JsonResponse({'status':'ok'}) 
     except User.DoesNotExist: 
      return JsonResponse({'status':'ok'}) 
    return JsonResponse({'status':'ok'}) 

我的HTML

{% extends 'base.html' %} 
{% load thumbnail %} 

{% block title %}{{ user.get_full_name }}{% endblock %} 

{% block content %} 
<h1>{{ user.get_full_name }}</h1> 
<div class="profile-info"> 
    {% thumbnail user.profile.photo '180x180' crop='100%' as im %} 
    <img src="{{ im.url }}" alt="profile photo"> 
    {% endthumbnail %} 
</div> 
{% with total_followers=user.followers.count %} 
<span class="count"> 
    <span class="total">{{ total_followers }}</span> 
    follower{{ total_followers|pluralize }} 
</span> 

<a href="#" data-id='{{ user.id }}' data-action='{% if request.user in user.followers.all %}un{% endif %}follow' class="follow button"> 
    {% if request.user not in user.followers.all %} 
    Follow 
    {% else %} 
    Unfollow 
    {% endif %} 
</a> 

<div id="image-list" class="image-container"> 
    {% include "images/image/list_ajax.html" with images=user.images_created.all %} 
</div> 
{% endwith %} 
{% endblock %} 

{% block domready %} 
$('a.follow').click(function(e){ 
e.preventDefault(); 
$.post('{% url "user_follow" %}', 
{ 
id: $(this).data('id'), 
action: $(this).data('action') 
}, 
function(data){ 
if (data['status'] == 'ok') { 
var previous_action = $('a.follow').data('action'); 
// toggle data-action 
$('a.follow').data('action', 
previous_action == 'follow' ? 'unfollow' : 'follow'); 

// update total followers 
var previous_followers = parseInt(
$('span.count .total').text()); 
$('span.count .total').text(previous_action == 'follow' ? 
previous_followers + 1 : previous_followers - 1); 
} 
} 
); 
}); 
{% endblock %} 

你需要从视图当你从阿贾克斯打来电话,与以前的更换HTML当前HTML,你将在成功得到(HTML模板代码动态返回)方法ajax

关注这个答案 Return JSON response using Django template system

编辑:

做应该有你要更改时调用Ajax请求的HTML代码模板。

html = render_to_string("yourtemplate.html", context_object) 
return JsonResponse({'status':'ok', 'html':html}) 

模板:

new_html = data['html'] 
    $selector = $('#id of block'); 
    $selector.html(new_html); 
+0

这个例子我必须写这个函数一个全新的看法? –

+0

无需编写新视图,在已存在的代码中添加额外内容。检查我的更新回答 –

+0

谢谢@NeErAj KuMaR工作 –