【问题标题】:How do I submit a form without page reload using Ajax如何使用 Ajax 在不重新加载页面的情况下提交表单
【发布时间】:2023-03-31 13:11:01
【问题描述】:

我正在学习 Ajax,了解如何在不重新加载页面的情况下提交评论表单。我正在使用 Django,我在主页上有帖子列表,每个帖子都有评论表格。当我提交评论时,它不会保存在数据库中,也不会显示在浏览器中。当我在 Chrome 控制台上检查时,我收到了一个错误 2 个元素具有非唯一 ID。

from django.http import JsonResponse
from django.template.loader import render_to_string

def home(request):
    all_images = Post.objects.filter(poster_profile=request.user)

    if request.method == 'POST':
        post_id = request.POST.get("post_comment")
        post_obj = Post.objects.get(pk=post_id)
        form = CommentForm(request.POST)
        if form.is_valid():
            comment=form.save(commit=False)
            comment.user=request.user
            comment.commented_image=post_obj
            comment.save()
    else:
        form=CommentForm()
context = {'all_images':all_images, 'form':form}
if request.is_ajax():
    html=render_to_string('ajax_feeds_comment.html', context, request=request) 
return render(request, 'home.html', context)

#home.html
{% for post in all_images %}
<img src="{{ post.image.url }}">
{% for comment in post.comments.all %}
<p>{{ comment.comment_post }}</p>
{% endfor %}
<div class="reload-form">
{% include "ajax_feeds_comments.html" %}
</div>
{% endfor %}

#ajax_feeds_comments.html
<form method="POST" class="feeds-comment" action=".">
{% csrf_token %}
<input type="hidden" value="{{post.id}}" name="post_comment">
<textarea name="comment_post" class="form-control" id="id_comment_post{{post.id}}"></textarea>
<button type="submit" class="btn btn-primary">submit</button>
</form>

<script>
$(document).on('submit', '.feeds-comment', function(event){
event.preventDefault();
console.log($(this).serialize());
$.ajax({
    type: 'POST', 
    url: $(this).attr('action'), 
    data: $(this).serialize(), 
    dataType: 'json', 
    success: function(response){
        $('.reload-form').html(response['form']);
   }, 
    error: function(rs, e) {
        console.log(rs,responseText);
   }, 
   });
   });
</script>

【问题讨论】:

    标签: python json django ajax


    【解决方案1】:

    这里有很多不正确的地方:

    1. 在您的“urls.py”中,您不应将每个请求都发送到您的视图。这是您得到“favico.ico”错误 500 的地方。没有 favico 是可以的,但得到错误 500 是不行的。
    2. 检查 html 代码是否有重复的 ID!这些必须是独一无二的。
    3. 如果您对 html 使用 django 变量,请执行以下操作: 使用“{{ post.id }}”代替“{{post.id}}”,并在 var 周围使用空格。
    4. document.on("submit", "feeds-comment", function(){...})

      您使用的不是该元素的 id,而是类名。

    5. 检查提交的去向。检查 Django 是否正在处理请求。 (您可以在运行 Django 的控制台中看到这一点)。也可以在这里张贴截图!

    【讨论】:

    • @gxor...我能够解决网站图标问题,控制台中没有 500 内部服务器错误。我在表单id中添加了{{ post.id }},仍然出现同样的问题
    • @gxor....我该如何解决这个问题,我按照你的指示,仍然是同样的问题。
    • 你在“if request.method == 'POST':”分支中得到了什么吗?你能检查一下吗? (只需打印一些东西)。否则它可能没有发送请求。检查您的浏览器开发工具(按 F12)并转到“网络分析”以查看是否出现了某些内容。
    • @gxor...当我提交我的第一个评论并检查控制台时,我得到了我的评论和 id 打印出来。但是当我提交第二条评论时,我在 chrome 控制台“未定义”中遇到错误
    • @gxor..我的主页上有两个帖子,当我提交评论时,我收到一个错误 2 个具有非唯一 ID 的元素,如果我在主页上有三个帖子,我收到一个错误 3 个元素具有非唯一 ID。即使我在 textarea 中添加了 {{ post.id }}
    猜你喜欢
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 2016-01-20
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    相关资源
    最近更新 更多