防止用户通过多次单击“提交”按钮来发布多个提交

prevent users to post multiple submission by clicking submit button multiple times

本文关键字:提交 按钮 布多个 单击 用户      更新时间:2023-09-26

这是我遇到的问题,当用户提交帖子并在加载新页面之前单击提交按钮两次时,就会发布两个相同的帖子。我以为我可以用 python 代码解决这个问题,因为我使用的是 django(限制用户在一分钟内只发布一个;我 http://dpaste.com/313A0A4 做了什么)但即使在那之后问题仍然存在。这是我的 html 代码(我的尝试不起作用)

{% block content %}
<form id="post_form" method="post" action="/add_post/" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form|crispy }}
<!--{% for tag in person.tags.all %}{{ tag.word }} {% endfor %}-->
     <input type="submit" name="submit" value="Create Post">
    </form>
    {% endblock %}
        {% include 'footer.html' %}
<script>

jQuery('form').on('submit', function(){ 
    if(jQuery("input[name=submit]").hasClass('active'))
        { return false; }
         else{ 
            jQuery("input[name=submit]").addClass('active'); } });
</script>

以下是我如何解决你的JavaScript问题。我假设表单在它自己的页面上,您必须在创建帖子后重定向到/posts

.HTML:

<form id="post-form" method="post">
  <p class="bg-danger" id="error-message"></p>
  <input id="submit-post-form" class="btn btn-primary" type="submit">
</form>

JavaScript:

$(function() {
    $('#post-form').submit(handleSubmit);
});
function handleSubmit(e) {
    var $submit = $('#submit-post-form');
    $submit.prop('disabled', true)
        .addClass('disabled')
        .attr('value', 'Please Wait...');
    // Let Python do it's thing
    var request = $.ajax({
        method: "POST",
        url: "add_post",
        data: $('#post-form').serialize()
    });
    // Once Python has inserted record in database
    request.done(function(response) {
        // Display error, if any occured
        if (response.error) {
           $('#error-message').html(response.error);
           $submit.prop('disabled', false)
                  .removeClass('disabled');
           return;
        }
        // Assuming posts are found at /posts
        window.location = 'posts';
        // If you want to get fancy with the redirect you can return it from python
        // window.location = response.url;
    });
    // Prevent regular submit functionality
    e.preventDefault();
    return false;
}
嗨,

请检查以下小提琴

https://jsfiddle.net/b5c75zjr/1/

.HTML

<input class="txt" type="text">
<input class="btn active" type="submit" name="submit" value="Create Post">

简讯

$(document).ready(function(){
 $('.btn').on('click', function(e){
 if($('.btn').hasClass('active'))
 {
 e.preventDefault();
 }
 else{
 $(this).addClass('active');
 alert('hi');
 }
 });
 $('.txt').on('change', function(){
 $('.btn').removeClass('active');
 });
});

也许类似的东西?