Django Ajax 表单提交错误地重定向到另一个页面 [英] Django Ajax Form submit wrongly redirect to another page

查看:26
本文介绍了Django Ajax 表单提交错误地重定向到另一个页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Django中使用ajax提交评论表单时,页面将重定向到一个空白页面,显示成功数据:

When I use ajax to submit a comment form in Django,the page will redirect to a blank page shows me the success data:

{"status":"success", "msg":"添加成功"}

,但不停留在当前页面.我希望页面停留在当前页面并显示新评论.

,but not stay in current page.I want the page stay in current page and show me the new comment.

这是我的 update_comment 视图:

Here is my update_comment view:

def update_comment(request, news_pk):
    news = get_object_or_404(News, id=news_pk)
    comment_form = CommentForm(request.POST or None)
    if request.method == 'POST' and comment_form.is_valid():
        if not request.user.is_authenticated:
            return render(request, 'login.html', {})
        comments = comment_form.cleaned_data.get("comment")
        news_comment = NewsComments(user=request.user, comments=comments, news=news)
        news_comment.save()

    # return redirect(reverse('news:news_detail', kwargs={'news_pk': news.id}))
        return HttpResponse('{"status":"success", "msg":"添加成功"}', content_type='application/json')
    else:
        return HttpResponse('{"status":"fail", "msg":"添加失败"}', content_type='application/json')

这是我的ajax:

$(document).on('submit', 'comment_form', function(e){
        e.preventDefault();

        $.ajax({
            cache: false,
            type: "POST",
            url:"{% url 'operation:update_comment' news.id %}",
            data:{'news_pk':{{ news.id }}, 'comments':comments},
            async: true,
            beforeSend:function(xhr, settings){
                xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
            },
            success: function(data) {
                if(data.status == 'fail'){
                    if(data.msg == '用户未登录'){
                        window.location.href="login";
                    }else{
                        alert(data.msg)
                    }
                }else if(data.status == 'success'){
                    window.location.reload();//refresh current page.
                }

                },
        });
    });

这是我的表格:

<form id="comment_form" action="{%  url 'operation:update_comment' news.id %}" method="POST" >
{% csrf_token %}

<textarea id="comment_textarea"name="comment"></textarea>

<input type="submit" value="Submit"> </input>

</form>

推荐答案

我终于成功了!感谢主!非常激动!

Finally I made it!Thanks Lord!Very excited!

我之前的代码有三个主要问题.

I have Three major issues in my previous code.

第一:由于ajax会将news_pk发布到视图update_comment,所以我不需要在这个视图的url和模板中添加news_pk(在

的url中) 标签和 ajax 中的 url),所以我删除了它们,否则数据仍然会通过 Form 而不是 ajax.

First:Since the ajax will post the news_pk to the view update_comment,so I don't need add news_pk in this view's url and template(in the url of <form> tag and the url in the ajax),so I removed them,or the data will still pass through Form but not ajax.

第二:我的绑定不正确,我在表单上有点击处理程序,它应该是提交处理程序.如果我将它绑定到一个按钮,那么我会使用单击处理程序.Ajax 在 Django 帖子中不起作用但是这部分我还是有点迷茫,按钮顶的方式和表单提交的方式.

Second:My binding is incorrect,I have the click handler on the form it should be a submit handler. If I was binding it to a button then I'd use click a handler.Ajax not work in Django post But for this part I'm still a some confused,between the button summit way and form submit way.

第三个问题是我把'comments'和'comment'弄错了.'comment'是