如何防止使用 jQuery 或 Javascript 进行双重提交?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2635652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I prevent a double submit with jQuery or Javascript?
提问by Odyss3us
I keep getting duplicate entries in my database because of impatient users clicking the submit button multiple times.
由于不耐烦的用户多次单击提交按钮,我的数据库中不断收到重复的条目。
I googled and googled and found a few scripts, but none of them seem to be sufficient.
我用谷歌搜索并用谷歌搜索并找到了一些脚本,但它们似乎都不够。
How can I prevent these duplicate entries from occurring using javascript or preferably jQuery?
如何使用 javascript 或最好使用 jQuery 防止这些重复条目发生?
Thanx in advance!
提前谢谢!
回答by Bill Paetzke
How about disabling the button on submit? That's what I do. It works fine.
禁用提交按钮怎么样?我就是做这个的。它工作正常。
$('form').submit(function(){
$('input[type=submit]', this).attr('disabled', 'disabled');
});
Disclaimer:
This only works when javascript is enabled on the user's browser. If the data that's being submitted is critical (like a credit card purchase), then consider my solution as only the first line of defense. For many use cases though, disabling the submit button will provide enough prevention.
免责声明:
这仅在用户浏览器上启用了 javascript 时才有效。如果提交的数据很关键(比如信用卡购买),那么我的解决方案只是第一道防线。但是,对于许多用例,禁用提交按钮将提供足够的预防。
I would implement this javascript-only solution first. Then track how many duplicate records are still getting created. If it's zero (or low enough to not care), then you're done. If it's too high for you, then implement a back-end database check for an existing record.
我会先实现这个 javascript-only 解决方案。然后跟踪仍有多少重复记录被创建。如果它为零(或低到不关心),那么你就完成了。如果它对您来说太高,那么对现有记录实施后端数据库检查。
回答by Sarfraz
This should do the trick:
这应该可以解决问题:
$("form").submit(function() {
$(":submit", this).attr("disabled", "disabled");
});
No JQuery?
没有 JQuery?
Alternatively, you can make a check from db to check if a record already exist and if so, don't insert new one.
或者,您可以从 db 进行检查以检查记录是否已存在,如果存在,则不要插入新记录。
回答by Flynn1179
One technique I've seen used is to assign a unique ID to every form that's opened, and only accept one submission per form based on the ID.
我见过的一种技术是为每个打开的表单分配一个唯一的 ID,并且每个表单只接受一个基于 ID 的提交。
It also means you can check how many times people aren't bothering to submit at all, and you can check if the submission genuinely came from your form by checking if it's got an ID that your server created.
这也意味着您可以检查人们根本不想提交的次数,并且您可以通过检查它是否有您的服务器创建的 ID 来检查提交是否真正来自您的表单。
I know you asked for a javascript solution, but personally I'd do both if I needed the robustness.
我知道你要求一个 javascript 解决方案,但如果我需要健壮性,我个人会同时做这两个。
回答by Nikola Petkanski
Preventing the double posting is not so simple as disabling the submit button. There are other elements that may submit it:
防止重复发布并不像禁用提交按钮那么简单。还有其他元素可以提交它:
- button elements
- img elements
- javascripts
- pressing 'enter' while on some text field
- 按钮元素
- 图片元素
- javascripts
- 在某些文本字段上按“输入”
Using jQuery data container would be my choice. Here's an example:
使用 jQuery 数据容器将是我的选择。下面是一个例子:
$('#someForm').submit(function(){
$this = $(this);
/** prevent double posting */
if ($this.data().isSubmitted) {
return false;
}
/** do some processing */
/** mark the form as processed, so we will not process it again */
$this.data().isSubmitted = true;
return true;
});
回答by Jim Schmehil
Here is bit of jQuery that I use to avoid the double click problem. It will only allow one click of the submit button.
这是我用来避免双击问题的一些 jQuery。它只允许单击提交按钮。
$(document).ready(function() {
$("#submit").on('click', function() {
});
});
回答by nulltek
I'm not sure what language/framework you're working with or if it's just straight HTML. But in a Rails app I wrote I pass a data attribute on the form button disable_withwhich keeps the button from being clickable more than once while the transaction is in process.
我不确定您正在使用什么语言/框架,或者它是否只是纯 HTML。但是在我编写的 Rails 应用程序中,我在表单按钮上传递了一个数据属性,disable_with这可以防止在事务处理过程中多次单击该按钮。
Here's what the ERB looks like.
这是 ERB 的样子。
<%= f.button "Log In", class: 'btn btn-large btn-block btn-primary', data: {disable_with: "<i class='icon-spinner'></i>Logging In..."} %>
回答by Changaco
This is what I came up with in https://github.com/liberapay/liberapay.com/pull/875:
这是我在https://github.com/liberapay/liberapay.com/pull/875 中提出的:
$('form').on('submit', function (e) {
var $form = $(this);
// Check that the form hasn't already been submitted
if ($form.data('js-submit-disable')) {
e.preventDefault();
return false;
}
// Prevent submitting again
$form.data('js-submit-disable', true);
// Set a timer to disable inputs for visual feedback
var $inputs = $form.find(':not(:disabled)');
setTimeout(function () { $inputs.prop('disabled', true); }, 100);
// Unlock if the user comes back to the page
$(window).on('focus pageshow', function () {
$form.data('js-submit-disable', false);
$inputs.prop('disabled', false);
});
});
回答by Jon
The problem with the method described hereis that if you're using a javascript validation framework and the validation fails, you won't be able to correct and re-submit the form without refreshing the page.
此处描述的方法的问题在于,如果您使用的是 javascript 验证框架并且验证失败,您将无法在不刷新页面的情况下更正和重新提交表单。
To solve this, you need to plug into the success event of your validation framework and only then, set the submit control to disabled. With Parsley, you can plug into the form validated event with the following code:
要解决此问题,您需要插入验证框架的成功事件,然后才将提交控件设置为禁用。使用Parsley,您可以使用以下代码插入表单验证事件:
$.listen('parsley:form:validated', function(e){
if (e.validationResult) {
/* Validation has passed, prevent double form submissions */
$('button[type=submit]').attr('disabled', 'disabled');
}
});
回答by Edward Brey
If you are using client-side validation and want to allow additional submit attempts if the data is invalid, you can disallow submits only when the form content is unchanged:
如果您正在使用客户端验证并希望在数据无效时允许额外的提交尝试,您可以仅在表单内容不变时禁止提交:
var submittedFormContent = null;
$('#myForm').submit(function (e) {
var newFormContent = $(this).serialize();
if (submittedFormContent === newFormContent)
e.preventDefault(true);
else
submittedFormContent = newFormContent;
});
回答by Artyom P
That is what I did to solve the problem.
I disabled the button for a second with adding setTimeouttwice:
-the 1st time is to let the JS form fields verification work;
-the 2nd time is to enable the button in case if you have any verification on your back end, that may return an error, and hence the user will want to try to submit the form again after editing his data.
这就是我为解决问题所做的。我通过两次添加setTimeout禁用了按钮一秒钟:
-第一次是让 JS 表单字段验证工作;
-第二次是启用该按钮,以防您在后端进行任何验证,这可能会返回错误,因此用户将希望在编辑其数据后再次尝试提交表单。
$(document).ready(function(){
$('button[type=submit]').on("click", function(){
setTimeout(function () {
$('button[type=submit]').prop('disabled', true);
}, 0);
setTimeout(function () {
$('button[type=submit]').prop('disabled', false);
}, 1000);
});
});

