django ajax提交form表单数据页面跳转问题
本帖最后由 kylin121380 于 2020-5-20 13:25 编辑点击提交后页面页面还是进行了跳转,请问哪里出了问题
html中ajax:
$("#comment_form").submit(function(){
// 更新数据到textarea
CKEDITOR.instances['id_text'].updateElement();
// 异步提交
$.ajax({
url: "{% url 'comment:comment_sub' %}",
type: 'POST',
data: $(this).serialize(),
cache: false,
success: function(data){
console.log(data);
if(data['status']=="SUCCESS"){
// 清空编辑框的内容
CKEDITOR.instances['id_text'].setData('');
}else{
// 显示错误信息
$("#comment_error").text(data['message']);
}
},
error: function(xhr){
console.log(xhr);
}
});
return false;
});
form:
<form id="comment_form" action="{% url 'comment:comment_sub' %}" method="POST">
{% csrf_token %}
{% for field in comment_form %}
{{field}}
{%endfor%}
<input type="submit" value="评论" class="btn btn-primary pull-right">
<hr>
</form>
后端views:
@csrf_exempt
def comment_sub(request):
referer = request.META.get('HTTP_REFERER', '/')# 跳转回原网页
comment_form = CommentForm(request.POST, user=request.user)
data = {}
if comment_form.is_valid():
comment = Comment.objects.create(
article_comment=comment_form.cleaned_data['comment_content'],
user=comment_form.cleaned_data['user'],
article=comment_form.cleaned_data['bbs'],
)
comment.save()
# return redirect(referer)
data['status'] = 'SUCCESS'
data['user'] = comment.user.username
data['text'] = comment.article_comment
data['comment_time'] = comment.date.strftime('%Y-%m-%d %H:%M:%S')
else:
# return render(request, '404.html', {'message': comment_form.errors, 'redirect_to': referer})
data['status'] = 'ERROR'
return JsonResponse(data) 提交后会自动跳转到原本指定页面,页面信息是jsonresponse返回的信息。 textarea的id写错了{:10_266:}CKEDITOR.instances['id_text'].updateElement();里面的id改成自己textarea的id就好了{:10_266:}
页:
[1]