|
10鱼币
本帖最后由 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)
复制代码 |
|