这是我遇到的问题,当用户提交帖子并在加载新页面之前单击两次提交按钮,然后创建两个相同的帖子。我以为我可以用python代码修复此问题,因为我使用的是django(限制用户每1分钟仅发布一次;即使该问题存在,我也做了http://dpaste.com/313A0A4)but。这是我的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;
}

关于javascript - 通过多次单击提交按钮来防止用户发布多个提交,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35355665/

10-12 19:00
查看更多