【问题标题】:Django, Ajax and JS . How to prevent page reloads and jump ups to the top of the page when i submit a commentDjango、Ajax 和 JS。提交评论时如何防止页面重新加载并跳转到页面顶部
【发布时间】:2021-03-12 15:43:09
【问题描述】:

我遵循了一个关于如何在不重新加载页面和跳转到页面顶部的情况下提交 Django 评论表单的解决方案。我尝试了许多在线和离线的解决方案,但仍然没有解决方案。

表单工作正常,唯一的问题是提交时页面重新加载。

我是 Django 后端和 Ajax 的新手,如果有人能帮助我解决这个问题,我会很高兴。提前致谢。

JS AJAX

$( document ).ready(function() {
           
    $(`.comment-form${post_id}`).submit(function() {
          $.ajax({
              data: $(this).serialize(), 
              type: $(this).attr('method'), 
              url: $(this).attr('action'), 
              success: function(response) {
                  $();
              },
              error: function(response) {
                console.log('error', response)
             }
          });
          return false;
    });
});
models.py

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
from django.db import models

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    body = models.TextField(max_length=300)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.pk)
VIEWS

from django.shortcuts import render, redirect
from .models import Post, Like
from django.contrib.auth.models import User
from .forms import CommentModelForm
from django.http import JsonResponse

# Create your views here.

def post_comment_create_and_list_view(request):
    qs = Post.objects.all()
    user = User.objects.get(pk=request.user.pk)


    #Comment form
    c_form = CommentModelForm()
        
    if 'submit_c_form' in request.POST:
        c_form = CommentModelForm(request.POST)
        if c_form.is_valid():
            instance = c_form.save(commit=False)
            instance.user = user
            instance.post = Post.objects.get(id=request.POST.get('post_id'))
            instance.save()
            c_form = CommentModelForm()

    
    context = {
    'qs': qs,
    'user':user,
    'c_form':c_form,
    }

    return render(request, 'posts/main.html', context)
HTML

<form action="" method="POST" class="comment-form" id='{{obj.id}}'>
{% csrf_token %}
  <div class="input-group">
    <input type="hidden" name="post_id" value={{obj.id}}> 
    
    {{ c_form }}
    <div class="input-group-append">
      <button type="submit" name="submit_c_form" class="btn btn-md u-btn-white g-color-red g-text-underline-hover g-brd-gray-light-v3 g-brd-none g-brd-top">Post</button>
      </div> 
    </div>
</form>

【问题讨论】:

  • 可以分享评论模型代码吗?这对您有任何帮助吗django-js-how-to-post-a-form-without-reloading-whole-page
  • 如果您指定哪些有效,哪些无效,将会很有帮助
  • @AjayLingayat 我现在添加了模型代码。感谢您的链接,将检查它。
  • @ha-neul 一切正常,唯一的问题是当我提交评论时页面会重新加载,我想防止这种情况发生。
  • @MoAlaneth 看到我的回答。

标签: javascript html python-3.x django


【解决方案1】:

您可以通过添加 e.preventDefault(); 来防止页面重新加载

$(`.comment-form${post_id}`).submit(function(e) { // Note here too, on submit a function in created where we catch e
      e.preventDefault(); // Here it is e is an event which is passed on clicking button
      $.ajax({
          data: $(this).serialize(), 
          type: $(this).attr('method'), 
          url: $(this).attr('action'), 
          success: function(response) {
              $();
          },
          error: function(response) {
            console.log('error', response)
         }
      });
      return false;
    });

【讨论】:

  • 尝试过,但当我提交 cmets 时页面仍然会重新加载。
  • 打开控制台查看是否有错误,并将该函数从就绪函数中退出
  • 这是我从控制台得到的:未捕获的 ReferenceError: post_id is not defined at HTMLDocument. ((index):568)
  • 我只用类名将 (.comment-form${post_id}) 更改为 ('.comment-form'),但现在表单除了阻止默认行为之外没有任何作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-26
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-21
相关资源
最近更新 更多