0

在用户单击按钮后,我正在禁用按钮,以防止重复提交或操作。我有两种类型的按钮。执行提交并重新加载页面的 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 按钮,这个按钮不会重新加载页面。当用户按下按钮时,它应该被禁用,直到使用按钮启动的过程结束,然后再次启用它。我可以检查按钮是否提交,或者它只是说清除表单中的所有字段。我在想也许我可以得到从按钮按下开始的过程,然后当它结束时我可以继续工作。这甚至可能吗?还是有其他解决方法?

4

2 回答 2

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/

如果有任何其他问题让我知道;)我希望这会有所帮助

于 2013-03-26T07:29:34.070 回答
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>
于 2013-03-26T07:24:01.617 回答