[英]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.