我正在努力在用户点击它们之后禁用按钮,以防止双重提交或操作。我有两种类型的按钮。一个php按钮(或表单按钮),用于提交并重新加载页面。我没有那个问题。因为我只是永远禁用按钮,并在重新加载后再次推送。这是一个例子:
$(document).on('click', 'button', function() {
var $this = $(this);
htmls = $(this).html();
$(this).prop("disabled", true);
setTimeout(function(){
$this.prop("disabled", false);
}, 2000);
});
这是2秒,但我将删除setTimeout部分。 更大的问题是Javascript按钮,这个按钮不会重新加载页面。 当用户按下按钮时,应该禁用该按钮,直到按钮开始的过程结束,然后再次启用它。 我可以检查按钮是否提交,或者只是让我们说清除表单中的所有字段。我想也许我可以得到按钮按下开始的过程,然后当它结束时我可以继续工作。这甚至可能吗?或者还有其他一些解决方法吗?
答案 0 :(得分:2)
您可以使用jQuery.ajax向服务器发出请求,并在响应从服务器返回时继续处理相同的表单或其他内容。您必须记住,您必须从表单中收集所有数据并将其作为json对象发送到服务器。
基于代码的小例子:
$(document).on('click', 'button', function() {
var $this = $(this);
htmls = $(this).html();
$(this).prop("disabled", true);
$.ajax({
type: "POST",
url: "some.php", //url to make post to
data: JSON.stringify(formdata), //data collected from your form
contentType: "application/json; charset=utf-8",
dataType: "json",
}).done(function( result) {
//put here the code to process the result from server
}).fail(function() {
alert("error"); // if something went wrong on server
})
.always(function() {
$(this).prop("disabled", false); //back enabling your button and maybe some other logic
});;
});
在此处阅读有关jQuery.ajax的更多信息http://api.jquery.com/jQuery.ajax/
如果有任何其他问题让我知道;) 我希望这会有所帮助
答案 1 :(得分:1)
你可以这样做
<input type='button' value='Javascript button' id="btn" />
<script>
$(document).ready(function () {
$("#btn").click(function () {
$(this).prop("disabled", true);
// long processing
$(this).prop("disabled", false);
});
//OR with a jquery request
$("#btn").click(function () {
$(this).prop("disabled", true);
$.ajax({
type: "POST",
url: "some url",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
sucess: function (data) { alert(data); }
}).always(function () {
$(this).prop("disabled", false);
});
});
});
</script>