如何临时禁用Ajax调用中的按钮?

时间:2019-07-02 11:08:22

标签: javascript ajax disabled-control prop

在我的Javascript代码中,我编写了一个Ajax调用,其中两个for loop周期调用了两个JSON文件;当发生某些事件并单击Search按钮时,将调用某些函数:显示包含来自API请求的数据的表。

我想在Ajax调用中查找这些数据时暂时禁用Search按钮,然后在执行操作后再次启用它,其方式类似于{{1 }}方法,但不必设置毫秒数(我以前无法指定毫秒数,具体取决于互联网连接的速度和其他因素...)。

如何在回调函数中临时设置setTimeout()?换句话说,如何在Ajax调用中临时禁用按钮?

3 个答案:

答案 0 :(得分:2)

您可以为此使用beforeSendcomplete

$.ajax({
    type: 'POST',
    url: url,
    data: data,
    beforeSend: function() {
        // disable your button here
        .prop("disabled", true);
    },
    success: function(data) {
        //success
    },
    error: function(xhr) { // if error occured
    },
    complete: function() {
        // enable your button here
        .prop("disabled", false);
    }
});

答案 1 :(得分:0)

将对象实例注入事件处理程序中。

在此处检出可能的事件处理程序:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress

而不是Console.log在那里叫我们的object.prop("disabled",false")

答案 2 :(得分:0)

使用JavaScript Fetch API

<!DOCTYPE html>
<html>

<body>

  <div>
    <button type="button" id="btn1" onclick="loadData()">Change Content</button>
    <div id="response">
    </div>
  </div>

  <script>
    function loadData() {

      document.getElementById("btn1").disabled = true;

      fetch("https://jsonplaceholder.typicode.com/todos/1")
        .then((resp) => resp.text()) // Transform the response into text
        .then((data) => {
          document.getElementById("response").innerHTML =
            data;
          document.getElementById("btn1").disabled = false;
        });

    }
  </script>

</body>

</html>

使用普通的旧javascript

<!DOCTYPE html>
<html>

<body>

  <div>
    <button type="button" id="btn1" onclick="loadData()">Change Content</button>
    <div id="response">
    </div>
  </div>

  <script>
    function loadData() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.status == 200) {
          document.getElementById("response").innerHTML =
            this.responseText;
        }
        document.getElementById("btn1").disabled = false;
      };

      xhttp.open("GET", "https://jsonplaceholder.typicode.com/todos/1", true);
      xhttp.send();
      document.getElementById("btn1").disabled = true;
      document.getElementById("response").innerHTML = '';
    }
  </script>

</body>

</html>