如何使用ajax函数发送表单而不刷新页面,我缺少什么?我必须使用rest-framework吗?

mik*_*raa 8 javascript python django ajax jquery

我正在尝试使用ajax发送我的评论表单,现在当用户插入评论时,整个页面都会刷新.我希望在没有页面刷新的情况下很好地插入它.所以我尝试了很多东西,但没有运气.因为我是初学者,所以我试着遵循许多教程链接; https://realpython.com/blog/python/django-and-ajax-form-submissions/ https://impythonist.wordpress.com/2015/06/16/django-with-ajax-a-modern-client-服务器通信实践/评论页-1 /#评论1631

我意识到我的问题是我很难在views.py和forms.py中操作我的代码因此在进行客户端编程(js和ajax)之前我需要再次设置我的后端(python代码)来设置阿贾克斯.有人可以帮我这个吗?我不知道如何设置我的后端....

  <div class="leave comment>
    <form method="POST" action='{% url "comment_create" %}' id='commentForAjax'>{% csrf_token %}
    <input type='hidden' name='post_id' value='{{ post.id }}'/>
    <input type='hidden' name='origin_path' value='{{ request.get_full_path }}'/>

    {% crispy comment_form comment_form.helper %}
    </form>
    </div>



<div class='reply_comment'>
    <form method="POST" action='{% url "comment_create" %}'>{% csrf_token %}
    <input type='hidden' name='post_id' id='post_id' value='{% url "comment_create" %}'/>
    <input type='hidden' name='origin_path' id='origin_path' value='{{ comment.get_origin }}'/>
    <input type='hidden' name='parent_id' id='parent_id' value='{{ comment.id }}' />
    {% crispy comment_form comment_form.helper %}

    </form>
    </div>

    <script>
     $(document).on('submit','.commentForAjax', function(e){
      e.preventDefault();

      $.ajax({
        type:'POST',
        url:'comment/create/',
        data:{
          post_id:$('#post_id').val(),
          origin_path:$('#origin_path').val(),
          parent_id:$('#parent_id').val(),
          csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
        },
        success:function(json){
Run Code Online (Sandbox Code Playgroud)

我不知道该怎么做......我试过但是失败了......这里发生了什么})

这是我的forms.py

class CommentForm(forms.Form):
    comment = forms.CharField(
        widget=forms.Textarea(attrs={"placeholder": "leave your thoughts"})
    )

    def __init__(self, data=None, files=None, **kwargs):
        super(CommentForm, self).__init__(data, files, kwargs)
        self.helper = FormHelper()
        self.helper.form_show_labels = False
        self.helper.add_input(Submit('submit', 'leave your thoughts', css_class='btn btn-default',))
Run Code Online (Sandbox Code Playgroud)

和我的views.py

def comment_create_view(request):
    if request.method == "POST" and request.user.is_authenticated() and request.is_ajax():
        parent_id = request.POST.get('parent_id')
        post_id = request.POST.get("post_id")
        origin_path = request.POST.get("origin_path")
        try:
            post = Post.objects.get(id=post_id)
        except:
            post = None

        parent_comment = None
        if parent_id is not None:
            try:
                parent_comment = Comment.objects.get(id=parent_id)
            except:
                parent_comment = None

            if parent_comment is not None and parent_comment.post is not None:
                post = parent_comment.post

        form = CommentForm(request.POST)
        if form.is_valid():
            comment_text = form.cleaned_data['comment']
            if parent_comment is not None:
                # parent comments exists
                new_comment = Comment.objects.create_comment(
                    user=MyProfile.objects.get(user=request.user),
                    path=parent_comment.get_origin, 
                    text=comment_text,
                    post = post,
                    parent=parent_comment
                    )
                return HttpResponseRedirect(post.get_absolute_url())
            else:
                new_comment = Comment.objects.create_comment(
                    user=MyProfile.objects.get(user=request.user),
                    path=origin_path, 
                    text=comment_text,
                    post = post
                    )
                return HttpResponseRedirect(post.get_absolute_url())
        else:
            messages.error(request, "There was an error with your comment.")
            return HttpResponseRedirect(origin_path)

    else:
        raise Http404
Run Code Online (Sandbox Code Playgroud)

即使在阅读了关于它的教程之后,我仍然非常不满意使用ajax ... json如何发挥作用以及我应该如何修改views.py ....有人可以解释他们是如何组合在一起的吗?并帮我完成这件事......

    else:
        raise Http404
Run Code Online (Sandbox Code Playgroud)

Hir*_*tel 6

请参阅submit()serialize()的官方文档并修改您的ajax,如下所示:

<script>
     $('#commentForAjax' ).submit(function(e){
      e.preventDefault();

      $.ajax({
        type:'POST',
        url:'comment/create/',  // make sure , you are calling currect url
        data:$(this).serialize(),
        success:function(json){              
          alert(json.message); 
          if(json.status==200){
             var comment = json.comment;
             var user = json.user;
             /// set `comment` and `user` using jquery to some element
           }             
        },
        error:function(response){
          alert("some error occured. see console for detail");
        }
      });
     });
Run Code Online (Sandbox Code Playgroud)

在后端,您将返回HttpResponseRedirect()将您的ajax调用重定向到某个URL(状态代码= 302).我建议返回任何json响应.

对于Django 1.7+添加行from django.http import JsonResponse来返回json响应

对于pre Django 1.7使用 return HttpResponse(json.dumps(response_data), content_type="application/json")

修改views.py的这一部分以返回Json响应

def comment_create_view(request):
# you are calling this url using post method 
if request.method == "POST" and request.user.is_authenticated():
    parent_id = request.POST.get('parent_id')
    post_id = request.POST.get("post_id")
    origin_path = request.POST.get("origin_path")
    try:
        post = Post.objects.get(id=post_id)
    except:
        # you should return from here , if post does not exists
        response = {"code":400,"message":"Post does not exists"}
        return HttpResponse(json.dumps(response), content_type="application/json")

    parent_comment = None
    if parent_id is not None:
        try:
            parent_comment = Comment.objects.get(id=parent_id)
        except:
            parent_comment = None

        if parent_comment is not None and parent_comment.post is not None:
            post = parent_comment.post

    form = CommentForm(request.POST)
  if form.is_valid():
        comment_text = form.cleaned_data['comment']
        if parent_comment is not None:
            # parent comments exists
            new_comment = Comment.objects.create_comment(
                user=MyProfile.objects.get(user=request.user),
                path=parent_comment.get_origin, 
                text=comment_text,
                post = post,
                parent=parent_comment
                )
            response = {"status":200,"message":"comment_stored",
             "user":new_comment.user, 
             "comment":comment_text,
            }
            return HttpResponse(json.dumps(response), content_type="application/json")
        else:
            new_comment = Comment.objects.create_comment(
                user=MyProfile.objects.get(user=request.user),
                path=origin_path, 
                text=comment_text,
                post = post
                )
            response = {"status":200,"message":"new comment_stored",
             "user":new_comment.user,
             "comment":comment_text,}
            return HttpResponse(json.dumps(response), content_type="application/json")
    else:
        messages.error(request, "There was an error with your comment.")
        response = {"status":400,"message":"There was an error with your comment."}
        return HttpResponse(json.dumps(response), content_type="application/json")
Run Code Online (Sandbox Code Playgroud)

您不必使用rest-framework.但是如果你为此目的使用rest-framework,它将很容易实现.


JRo*_*ite 1

在完全审查了您的代码并与OP进行了详细讨论之后。我已经成功解决了 OP 问题。

\n\n
    \n
  1. 删除后,HttpResponseRedirect我首先将其转换为JsonResponse并进行相应的更改。

    \n\n
    response_data = {\n                     "status":200, "message":"comment_stored", \n                     "parent": True, \n                     "parent_id": parent_comment.id,\n                     "comment_count": parent_comment.comment_count()\n                 }\nreturn JsonResponse(response_data)\n
    Run Code Online (Sandbox Code Playgroud)
  2. \n
  3. 下一步是简单地执行 DOM 操作来显示从响应中获取的数据。但事实证明这比预想的要复杂。因此,为了简化它,我简单地将模板分为两部分 - 一部分是主要部分,另一部分仅包含注释的 HTML。

    \n\n

    我使用django.template.loader.render_to_string它生成了显示评论所需的 HTML,并以 JSON 字符串的形式与响应一起发送。

    \n\n
    html = render_to_string(\'main/child_comment.html\', \n                                 {\'comment\': [new_comment], \n                                  \'user\': request.user, \n                                  \'comment_form\':comment_form\n                        })\nresponse_data = { \n                    "status":200, "message":"comment_stored", \n                    "comment":html, \n                    "parent": True, "parent_id": parent_comment.id,\n                    "comment_count": parent_comment.comment_count()\n                }\nreturn JsonResponse(response_data)\n
    Run Code Online (Sandbox Code Playgroud)
  4. \n
  5. 最后,主要在 DOM 操作脚本和表单模型之一中进行一些小的更改(与当前问题无关)后,代码按预期工作。

    \n\n
    $(\'form\').submit(function(e) {\n    e.preventDefault();\n    if ($(this).parents("tr") != 0) {\n        parent_id = $(this).parents("tr").attr("id").split("_")[1];\n        data_str = $(this).serialize() + "&parent_id=" + parent_id;\n    } else {\n        data_str = $(this).serialize();\n    }\n    $(this).parents("tr").attr("id").split("_")[1]\n    $.ajax({\n        type: \'POST\',\n        url: \'{% url \'comment_create\' %}\',\n        data: data_str,\n        success: function(json) {\n            alert(json.message);\n            if (json.status == 200) {\n                var comment = json.comment.trim();\n                var user = json.user;\n                if (!json.parent) {\n                    $(comment).insertBefore(\'.table tr:first\');\n                } else {\n                    $(comment).insertBefore(\'#comment_\' + json.parent_id + \' #child_comment:first\');\n                    $(".replies").text("\xeb\x8b\xb5\xea\xb8\x80" + json.comment_count + "\xea\xb0\x9c \xeb\xaa\xa8\xeb\x91\x90 \xeb\xb3\xb4\xea\xb8\xb0");\n                }\n            }\n\n        },\n        error: function(response) {\n            alert("some error occured. see console for detail");\n        }\n    });\n});\n
    Run Code Online (Sandbox Code Playgroud)
  6. \n
  7. 额外提示:我们还遇到了另一个小问题,但我不会在这里讨论它。我已经为此写了一个单独的答案。

  8. \n
\n