我如何排队jQuery ajax请求

时间:2018-10-01 20:48:54

标签: jquery ajax

AJAX的新功能,我建立了一个包含AJAX的表单,该表单会将数据发送到另一个页面。我不确定是否必须包含用于多个ajax请求的插件,或者这是否自动完成。到目前为止,问题是$(“#userForm”)[0] .reset();。将等到完全成功后再清除输入字段。我希望它能够立即发送并清除,从而允许用户快速输入请求并为完成请求建立队列。

下面是我的表单/ ajax

<html>
<head>
<title>fastPage</title>
</head>
<body>
<form id='userForm'>
<div><input type='text' name='name' /></div>
<div><input type='submit' value='Submit' /></div>
</form>

<div id='response'></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>

<script>
<script>
$(document).ready(function(){
    $('#userForm').submit(function(){
        // show that something is loading
        //$('#response').html("<b>Loading response...</b>");
        // Call ajax for pass data to other place
        $.ajax({
            type: 'POST',
            url: 'slowPage.php',
            data: $(this).serialize() // getting filed value in serialize form
        })
        .done(function(data){ // if getting done then call.
            // show the response
            //$('#response').html(data);
            $("#userForm")[0].reset();
        })
        .fail(function() { // if fail then getting message
            // just in case posting your form failed
            alert( "Posting failed." );
        });
        // to prevent refreshing the whole page page
        return false;
    });
});
</script>
</body>
</html>

slowPage.php只是为了测试ajax调用。

<!DOCTYPE html>
<html>
<head>
<title>slowPage</title>
</head>

<?php
session_start();
echo "
    <form action='slowPage.php' method='POST'>
        <input type='text' name='name'>
        <button type='submit'>Search</button>
    </form>";
sleep(10);  
if($_POST){
    echo $_POST['name'];
}

?>

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:-1)

执行此操作的一种方法是构建自己的队列代理,该代理将立即执行推送到队列的请求,同时一次最多执行1个请求。当前请求完成处理后,它将自己从队列中删除,并立即启动队列中的下一个请求。

下面的代码是任何Promise对象的通用案例,但是,您可以像这样修改传入的内容以使其满足您的需求:

ajaxQueue.addRequest(function() {
  return $.ajax({
    // my ajax options
  })
  .done(function () {
    // ...
  })
  .fail(function () {
    // ...
  });
});

$(function () {
  var ajaxQueue = {
    queuedRequests: [],
    addRequest: function (req) {
      this.queuedRequests.push(req);
      // if it's the first request, start execution
      if (this.queuedRequests.length === 1) {
        this.executeNextRequest();
      }
    },
    clearQueue: function () {
      this.queuedRequests = [];
    },
    executeNextRequest: function () {
      var queuedRequests = this.queuedRequests;
      console.log("request started");
      queuedRequests[0]().then(function (data) {
        console.log("request complete", data);
        // remove completed request from queue
        queuedRequests.shift();
        // if there are more requests, execute the next in line
        if (queuedRequests.length) {
          ajaxQueue.executeNextRequest();
        }
      });
    }
  };
  $("#myForm").on("submit", function () {
    var data = $(this).serialize();
    // reset form right after we grab the data
    $(this)[0].reset();
    ajaxQueue.addRequest(function () {
      // -- your ajax request goes here -- 
      // return $.ajax({
      //   method: "POST",
      //   url: 'slowPage.php',
      //   data: data 
      // }).done(function () { ... }).fail(function () { ... });
      
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          resolve(data);
        }, 2000);
      });
    });
    return false;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<label>Send Data: <input name="myData"/></label><br/>
<button>Submit Form</button>
</form>