如何使用ajax函数发送表单而不刷新页面,我缺少什么?我必须使用rest-framework吗? [英] how to use ajax function to send form without page getting refreshed, what am I missing?Do I have to use rest-framework for this?

查看:63
本文介绍了如何使用ajax函数发送表单而不刷新页面,我缺少什么?我必须使用rest-framework吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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-第1页/#comment-1631

I'm trying to send my comment form using ajax, right now when user inserts a comment then whole page gets refreshed. I want this to be inserted nicely without page getting refreshed. So I tried bunch of things but no luck. since I'm a beginner, I tried to follow many tutorial links; 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 $中操作我的代码b $ b因此在进行客户端编程(js和ajax)之前,我需要再次设置我的后端(python代码)来为ajax设置。
有人可以帮我这个吗?
我不知道如何设置我的后端......

I realize my problem is that I have a hard time manipulating my code in views.py and forms.py Thus before doing a client side programming(js and ajax) I need to set my backend(python code) again to be set for the ajax. Can someone please help me with this? I don't know how to set my backend....

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

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

I don't know what to do here...I tried it but failing....what is going on here })

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

和my views.py

and my 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

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

I'm still very shaky on the idea of using ajax even after reading a tutorial about it...how json comes into play and how I should modify views.py too....can someone please explain how they all group together?and help me getting this done...

    else:
        raise Http404


推荐答案

完全检查代码并与OP讨论后长度。我已设法解决OP问题。

After completely reviewing your code and discussing with OP in length. I've managed to resolve the OPs issue.


  1. 删除 HttpResponseRedirect 我首先将其转换为 JsonResponse 并相应地进行了更改。

  1. After removing HttpResponseRedirect I first converted it to JsonResponse and made changes accordingly.

response_data = {
                     "status":200, "message":"comment_stored", 
                     "parent": True, 
                     "parent_id": parent_comment.id,
                     "comment_count": parent_comment.comment_count()
                 }
return JsonResponse(response_data)


  • 下一步是简单地执行DOM操作以显示从响应中获取的数据。但事实证明这比预期更复杂。因此,为了简化它,我简单地将模板分成两部分 - 一部分将是主要部分,另一部分仅包含评论的HTML。

  • Next step was to simply perform DOM manipulation to display the data fetched from the response. But turns out this was more complicated than expected. So, to simplify it I simply separated the template into 2 parts - one will be the main part and the other containing the HTML of only the comment.

    使用 django.template.loader.render_to_string 我生成了所需的HTML来显示注释,并将响应作为字符串发送到JSON中。

    Using django.template.loader.render_to_string I generated the required HTML to display the comment and sent with the response as a string in JSON.

    html = render_to_string('main/child_comment.html', 
                                     {'comment': [new_comment], 
                                      'user': request.user, 
                                      'comment_form':comment_form
                            })
    response_data = { 
                        "status":200, "message":"comment_stored", 
                        "comment":html, 
                        "parent": True, "parent_id": parent_comment.id,
                        "comment_count": parent_comment.comment_count()
                    }
    return JsonResponse(response_data)
    


  • 最后,在主要在DOM操作脚本和其中一个表单模型中进行微小更改(与当前问题无关)之后,代码按预期工作。

  • Finally, after minor changes (not relevant to the current issue) mainly in the DOM manipulation scripts and in one of the form models, the code worked as expected.

    $('form').submit(function(e) {
        e.preventDefault();
        if ($(this).parents("tr") != 0) {
            parent_id = $(this).parents("tr").attr("id").split("_")[1];
            data_str = $(this).serialize() + "&parent_id=" + parent_id;
        } else {
            data_str = $(this).serialize();
        }
        $(this).parents("tr").attr("id").split("_")[1]
        $.ajax({
            type: 'POST',
            url: '{% url 'comment_create' %}',
            data: data_str,
            success: function(json) {
                alert(json.message);
                if (json.status == 200) {
                    var comment = json.comment.trim();
                    var user = json.user;
                    if (!json.parent) {
                        $(comment).insertBefore('.table tr:first');
                    } else {
                        $(comment).insertBefore('#comment_' + json.parent_id + ' #child_comment:first');
                        $(".replies").text("답글" + json.comment_count + "개 모두 보기");
                    }
                }
    
            },
            error: function(response) {
                alert("some error occured. see console for detail");
            }
        });
    });
    


  • BONUS:还有另一个未成年人我们遇到过的问题但我不会在这里讨论。我为它写了一个单独的答案

  • BONUS: There was another minor issue which we had faced but I won't discuss it here. I've written a separate answer for it.

    这篇关于如何使用ajax函数发送表单而不刷新页面,我缺少什么?我必须使用rest-framework吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆