使用 ajax 作为注释表单,它给了我 500 个内部错误,但没有脚本它可以工作,这意味着我的脚本是错误的;对

using ajax for comment form, it gives me 500 internal error but without script it works which means my script is wrong;right?

本文关键字:脚本 错误 工作 ajax 意味着 我的 表单 使用 内部 注释      更新时间:2023-09-26

我有有效的评论系统(至少在后端工作)。问题是每次用户提交评论时,页面都会刷新。我为此编写了一个 ajax 函数,但由于我是初学者,我本以为会出现错误,我做到了。我有 500 个内部错误。我不确定我做错了什么。这是我的代码

<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(){
      alert('it worked');
    }
  })
 })
</script>

我有这样的网址

   url(r'^comment/create/$', 'comment_create_view', name='comment_create'),

编辑:

我没有发布我的 views.py,因为它很大,并认为我写错了ajax。我会发布我的观点

def comment_create_view(request):
    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:
            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
                    )
                #affected_users = parent_comment.get_affected_users()
                #print "this is"
                affected_users = parent_comment.get_affected_users()
                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

我忘了在这里添加这个

urlpatterns += patterns('comments.views',

编辑二,我使用 class for commentForAjax 而不是 id 的原因是因为我也想对我的回复注释代码产生相同的效果。我想要一个 ajax 函数用于我的两个表单。

<div class="make_reply">
    <a href='#' class='reply_btn'>reply</a>
        <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>
    </div>

编辑:这是我的 Django 错误,我不知道该怎么做,但遵循了丹尼尔的指导。是这个吗?运行时错误在/comment/create您通过 POST 调用了此 URL,但该 URL 不以斜杠结尾,并且您已设置APPEND_SLASH。Django 在维护 POST 数据时无法重定向到斜杠 URL。将表单更改为指向 127.0.0.1:8000/comment/create/(注意尾部斜杠),或在 Django 设置中设置 APPEND_SLASH=False。

Request Method: POST
Request URL: http://127.0.0.1:8000/comment/create
Django Version: 1.8.4
Python Executable: env/bin/python
Python Version: 2.7.6
Python Path: [ 'env/lib/python2.7', 'env/lib/python2.7/plat-x86_64-linux-gnu', 'env/lib/python2.7/lib-tk', 'env/lib/python2.7/lib-old', 'env/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', 'env/local/lib/python2.7/site-packages', 'env/lib/python2.7/site-packages']
Server time: 화요ì¼, 15 3ì›” 2016 18:48:14 +0900
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'main',
 'comments',
 'notifications',
 'news',
 'tastypie',
 'userena',
 'guardian',
 'easy_thumbnails',
 'accounts',
 'crispy_forms',
 'django_select2',
 'actstream',
 'annoying',
 'embed_video',
 'ckeditor',
 'ckeditor_uploader',
 'whoosh',
 'haystack')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')
Traceback:
File "env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  108.                 response = middleware_method(request)
File "env/local/lib/python2.7/site-packages/django/middleware/common.py" in process_request
  84.                     "settings.") % (new_url[0], new_url[1]))
Exception Type: RuntimeError at /comment/create
Exception Value: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/comment/create/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.
Request information:
GET: No GET data
POST:
post_id = u'/comment/create/'
csrfmiddlewaretoken = u'gw8ohxs2ZPVonPf812iM3vCAK2NnxAde'
parent_id = u'216'
FILES: No FILES data

您发布的异常非常有用:

异常值:您通过 POST 调用了此 URL,但该 URL 不以斜杠结尾,并且您已设置APPEND_SLASH。Django 在维护 POST 数据时无法重定向到斜杠 URL。将表单更改为指向 127.0.0.1:8000/comment/create/(注意尾部斜杠),或在 Django 设置中设置 APPEND_SLASH=False。 索取信息:

因此,您必须在 ajax 方法中的 url 中添加尾部斜杠:

<script>
 $(document).on('submit','.commentForAjax', function(e){
  e.preventDefault();
  $.ajax({
    type:'POST',
    url:'/comment/create/',  //ADD THE SLASH!
    data:{
      post_id:$('#post_id').val(),
      origin_path:$('origin_path').val(),
      parent_id:$('#parent_id').val(),
      csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
    },
    success:function(){
      alert('it worked');
    }
  })
 })
</script>

你的脚本有问题。

<script>
    ...
    origin_path:$('origin_path').val(),
    ...
</script>

origin_path是 ID 而不是标签。替换为此

<script>
    ...
    origin_path:$('#origin_path').val(),
    ...
</script>

如需更多帮助,您应该打印服务器错误消息