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

2023-11-26

我正在尝试使用 ajax 发送评论表单,现在当用户插入评论时,整个页面都会刷新。我希望能够很好地插入此内容,而无需刷新页面。 所以我尝试了很多东西但没有运气。由于我是初学者,我尝试遵循许多教程链接;https://realpython.com/blog/python/django-and-ajax-form-submissions/ https://impythonist.wordpress.com/2015/06/16/django-with-ajax-a-modern-client-server-communication-practise/comment-page-1/#comment-1631

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

  <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){

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

这是我的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',))

和我的观点.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

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

    else:
        raise Http404

参见官方文档submit() and 连载()并像这样修改你的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");
        }
      });
     });

在后端你正在返回HttpResponseRedirect()这会将您的 ajax 调用重定向到某个 url(状态代码=302)。我建议返回任何 json 响应。

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

对于 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")

您不必使用休息框架。但如果你使用rest-framework来实现这个目的,那么它会很容易实现。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用ajax函数发送表单而不刷新页面,我错过了什么?我必须使用rest-framework吗? 的相关文章