繁体   English   中英

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

[英]prevent users to post multiple submission by clicking submit button multiple times

这是我遇到的问题,当用户提交帖子并在加载新页面之前单击两次提交按钮,然后创建两个相同的帖子。 我以为我可以用python代码解决此问题,因为我使用的是django(限制用户每1分钟只能发布一次;我的操作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>

嗨,请检查以下小提琴

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

HTML

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

JQUERY

$(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');
 });
});

也许类似的东西?

这就是我用JavaScript解决您的问题的方法。 我假设表单在其自己的页面上,并且您必须在创建/posts后重定向到/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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM