Django,Ajax和JS.当我提交评论时,如何防止页面重新加载并跳至页面顶部 [英] Django, Ajax and JS . How to prevent page reloads and jump ups to the top of the page when i submit a comment

查看:35
本文介绍了Django,Ajax和JS.当我提交评论时,如何防止页面重新加载并跳至页面顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循了一个解决方案,该解决方案是如何使Django注释表单提交而无需重新加载页面并跳转到页面顶部.我在线上和线下尝试了许多解决方案,但仍然没有解决方案.

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

我是Django Backend和Ajax的新手,如果有人可以提供帮助,我将很高兴.预先感谢.

  JS AJAX$(document).ready(function(){$(`.comment-form $ {post_id}`).submit(function(){$ .ajax({数据:$(this).serialize(),类型:$(this).attr('method'),网址:$(this).attr('action'),成功:功能(响应){$();},错误:功能(响应){console.log('错误',响应)}});返回false;});});  

  models.py从django.db导入模型从django.contrib.auth.models导入用户#在此处创建模型.从django.db导入模型类Comment(models.Model):user = models.ForeignKey(User,on_delete = models.CASCADE)post = models.ForeignKey(Post,on_delete = models.CASCADE)正文= models.TextField(max_length = 300)更新= models.DateTimeField(auto_now = True)创建= models.DateTimeField(auto_now_add = True)def __str __():返回str(self.pk) 

  VIEWS从django.shortcuts导入渲染,重定向来自.models import帖子,赞从django.contrib.auth.models导入用户从.forms导入CommentModelForm从django.http导入JsonResponse#在这里创建您的视图.def post_comment_create_and_list_view(request):qs = Post.objects.all()用户= User.objects.get(pk = request.user.pk)#评论表格c_form = CommentModelForm()如果在request.POST中为"submit_c_form":c_form = CommentModelForm(request.POST)如果c_form.is_valid():实例= c_form.save(commit = False)instance.user =用户instance.post = Post.objects.get(id = request.POST.get('post_id'))instance.save()c_form = CommentModelForm()上下文= {'qs':qs,'用户':用户,'c_form':c_form,}返回render(request,'posts/main.html',上下文) 

  HTML< form action =""method ="POST"class ="comment-form"id ='{{obj.id}}'>{%csrf_token%}< div class =输入组"><输入类型=隐藏的".name ="post_id";值= {{{obj.id}}>{{c_form}}< div class ="input-group-append"< button type =提交";名称="submit_c_form";class ="btn btn-md u-btn白色g-红色-g-text-下划线-悬停在g-brd-gray-light-v3 g-brd-none g-brd-top">帖子</按钮></div></div></form> 

解决方案

您可以通过添加 e.preventDefault();

来防止页面重新加载

  $(`.comment-form $ {post_id}`).submit(function(e){//还要注意,在创建函数时在提交时捕获ee.preventDefault();//这是e是单击按钮时传递的事件$ .ajax({数据:$(this).serialize(),类型:$(this).attr('method'),网址:$(this).attr('action'),成功:功能(响应){$();},错误:功能(响应){console.log('错误',响应)}});返回false;}); 

I followed a solution on how to get Django comment form to submit without page reloading and jumping to the top of the page. I tried many solutions online and offline but still no solution.

The form works correctly, the only problem is the page reload on submit.

I am new to Django Backend and Ajax, I will be happy if someone can help on how to deal with this. Thanks in Advance.

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>

解决方案

You prevent page reload by adding 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;
    });

这篇关于Django,Ajax和JS.当我提交评论时,如何防止页面重新加载并跳至页面顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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