Javascript 在我的ajax请求发生在django中的文本之前,必须刷新页面
我有一个follow按钮,它使用ajax,Javascript 在我的ajax请求发生在django中的文本之前,必须刷新页面,javascript,jquery,python,ajax,django,Javascript,Jquery,Python,Ajax,Django,我有一个follow按钮,它使用ajax,{{total_followers}}可以通过单击增加或减少来很好地工作,但是follow和unfollow按钮只有在我刷新整个页面时才会更改,这是我不想要的 我的观点 @ajax_required @require_POST @login_required def user_follow(request): user_id = request.POST.get('id') action = request.POST.get('actio
{{total_followers}}
可以通过单击增加或减少来很好地工作,但是follow和unfollow按钮只有在我刷新整个页面时才会更改,这是我不想要的
我的观点
@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%}
{%加载缩略图%}
{%block title%}{{user.get_full_name}{%endblock%}
{%block content%}
{{user.get_full_name}
{%thumbnail user.profile.photo'180x180'crop='100%'作为im%}
{%endthumbnail%}
{%的追随者总数=user.followers.count%}
{{total_followers}}
追随者{{total_followers | pluralize}}
{%include“images/image/list_ajax.html”,其中images=user.images_created.all%}
{%endwith%}
{%endblock%}
{%block-domready%}
$('a.follow')。单击(函数(e){
e、 预防默认值();
$.post(“{%url”用户_follow“%}”,
{
id:$(this).data('id'),
操作:$(this).data('action')
},
功能(数据){
如果(数据['status']=='ok'){
var previous_action=$('a.follow')。数据('action');
//切换数据操作
$('a.follow').data('action',
上一个动作==“跟随”?“取消跟随”:“跟随”);
//更新追随者总数
var previous_followers=parseInt(
$('span.count.total').text();
$('span.count.total').text(上一个操作=='follow'?
前_追随者+1:前_追随者-1);
}
}
);
});
{%endblock%}
当您从ajax调用时,您需要从视图动态返回html模板代码,并将html替换为当前html,这样您将在成功ajax方法中获得html
遵循这个答案
编辑:
new_html = data['html']
$selector = $('#id of block');
$selector.html(new_html);
制作一个模板,该模板应该包含在调用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);
在这个例子中,我必须为这个函数编写一个完整的新视图吗?不需要编写新视图,在已经存在的代码中添加额外的视图。检查我的最新答案