Jquery在同步调用上禁用按钮

时间:2017-07-12 17:58:59

标签: javascript jquery ajax

我正在尝试禁用按钮以防止在同步ajax调用中多次单击。我的代码如下。

<!DOCTYPE html>
<html>
	<head>
	 <meta charset="UTF-8"> 
		<link type="text/css" rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <!-- optional font -->
		<script  src="https://code.jquery.com/jquery-3.2.1.min.js"  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="  crossorigin="anonymous"></script>
   		<script type="text/javascript">
        $(document).ready(function(){
        	var test = false;
            $(document).on('click', '#test', function(e){
            	console.log(test);
            	if (test) {
            		return;
            	}
            	test = true;
                ajax_call();
  
            });

            function ajax_call() {
            	$.ajax({
                    contentType: 'application/json;charset=utf-8',
                    type: 'POST',
                    url: 'https://validdomain',
                    dataType: 'json',
                    xhrFields: {
                      withCredentials: true
                    },
                    crossDomain: true,
                    data: JSON.stringify({'test' : 'test'}),
                    success: function(data, textStatus, jqXHR) {
                        console.log(data);test =false;
                        copypaste();
                        test = false;
                    },
                    error: function(jqXHR, textStatus, errorThrown) { 
                        console.log(textStatus);
                        
                        test = false;
                    },
                    async: false,
                });
            }

            function copypaste() {
            	var tempInput = document.createElement("textarea");
                tempInput.setAttribute('id', 'copyid');
                tempInput.style = "position: absolute; left: -1000px; top: -1000px";
                tempInput.value = 'Text Copied';
                console.log(tempInput);
                document.body.appendChild(tempInput);
                tempInput.select();
                var result = document.execCommand('copy');
               	document.body.removeChild(tempInput);
                if (result) {
                    alert('copied');
                }
                else {
                	alert('not copied');
                }

                return result;
            }

        });
    </script>
	</head>
	<body>
		<input type="submit" id="test"/>
	</body>
</html>

但是我的按钮在第二次点击时没有被禁用(我正在收到警报两次。)。如果我将ajax请求作为异步调用,则禁用按钮。有没有什么办法可以在同步通话期间禁用我的按钮?

提前致谢!

3 个答案:

答案 0 :(得分:0)

我添加了必要的声明但你可以把它放到另一个地方,例如在ajax回调函数中。我还改变了async: false

<!DOCTYPE html>
<html>
	<head>
	 <meta charset="UTF-8"> 
		<link type="text/css" rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <!-- optional font -->
		<script  src="https://code.jquery.com/jquery-3.2.1.min.js"  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="  crossorigin="anonymous"></script>
   		<script type="text/javascript">
        $(document).ready(function(){
        	var test = false;
            $(document).on('click', '#test', function(e){
            	console.log(test);
            	if (test) {
            		return;
            	}
            	test = true;
                ajax_call();
                //Try adding this statement you can add wherever you want
                $(document).off('click', '#test');
  
            });

            function ajax_call() {
            	$.ajax({
                    contentType: 'application/json;charset=utf-8',
                    type: 'POST',
                    url: 'https://validdomain',
                    dataType: 'json',
                    xhrFields: {
                      withCredentials: true
                    },
                    crossDomain: true,
                    data: JSON.stringify({'test' : 'test'}),
                    success: function(data, textStatus, jqXHR) {
                        console.log(data);test =false;
                        copypaste();
                        test = false;
                    },
                    error: function(jqXHR, textStatus, errorThrown) { 
                        console.log(textStatus);
                        
                        test = false;
                    },
                    async: true,
                });
            }

            function copypaste() {
            	var tempInput = document.createElement("textarea");
                tempInput.setAttribute('id', 'copyid');
                tempInput.style = "position: absolute; left: -1000px; top: -1000px";
                tempInput.value = 'Text Copied';
                console.log(tempInput);
                document.body.appendChild(tempInput);
                tempInput.select();
                var result = document.execCommand('copy');
               	document.body.removeChild(tempInput);
                if (result) {
                    alert('copied');
                }
                else {
                	alert('not copied');
                }

                return result;
            }

        });
    </script>
	</head>
	<body>
		<input type="submit" id="test"/>
	</body>
</html>

答案 1 :(得分:0)

为什么不简单地禁用按钮并重新启用它而不是声明像$("#test").attr('disabled','disabled')这样的全局变量?变量范围在javascript中会变得棘手。

答案 2 :(得分:0)

你碰巧在寻找像这样简单的东西?

PS:你必须自己输入ajax电话的详细信息。

<强> HTML

<button id="button">Button</button>

<强>的jQuery / JS

$("#button").click(function(){
   console.log("clicked");
   // deactivate button
   $("#button").attr("disabled", true);
   ajaxCall();

});

function ajaxCall(){
    $.ajax({
    //...ajax call here,
    complete: function(){
      // reactivate button after you receive any reply from ajax
      $("#button").attr("disabled", false);
    }
    })
}
相关问题