如何使用 Ajax 一次仅按顺序发布数组的 1 个值,并在继续之前等待响应


How do I use Ajax to Post only 1 value of an array at a time sequentially and wait for the response before proceeding?

我有一个Ajax Jquery脚本,它应该将日期数组发布到php页面得到一个结果,如果它是正确的结果,它会在页面上的div中显示成功消息,如果它不是正确的返回结果,它会显示错误。应该发生的事情是每个日期应该一次发送 1 个,等待响应,然后再移动到下一个。脚本似乎工作正常,但我注意到日期以随机顺序返回。经过调查,我了解到这是因为Ajax调用同时发送多个请求。我想这就是为什么它被称为异步JavaScript和XML(Lol(。无论如何,我已经为此工作了几个小时,似乎找不到或理解解决此问题的方法。我读过一些关于Javascript承诺和各种东西的东西,但我不明白。如果有人可以帮助一些代码帮助,那将不胜感激!

以下是包含Javascript和Ajax Call的整个HTML文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dates Range</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha256-7s5uDGW3AHqw6xtJmNNtr+OBRJUlgkNJEo78P4b0yRw= sha512-nNo+yCHEyn0smMxSswnf/OnX6/KwJuZTlNZBjauKhTK0c+zT+q5JOCx0UFhXQ6rJR9jg6Es8gPuD2uZcYDLqSw==" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-1.12.0.js"></script>
</head>
<script>
    $(function(){ startProcess({"7":"2016-01-07","8":"2016-01-08","9":"2016-01-09","10":"2016-01-10","11":"2016-01-11","12":"2016-01-12","13":"2016-01-13","14":"2016-01-14","15":"2016-01-15","16":"2016-01-16","17":"2016-01-17","18":"2016-01-18","19":"2016-01-19","20":"2016-01-20","21":"2016-01-21","22":"2016-01-22","23":"2016-01-23","24":"2016-01-24","25":"2016-01-25","26":"2016-01-26","27":"2016-01-27","28":"2016-01-28","29":"2016-01-29","30":"2016-01-30","31":"2016-01-31","32":"2016-02-01","33":"2016-02-02","34":"2016-02-03","35":"2016-02-04","36":"2016-02-05"});
        // Ajax to send Date
        function startProcess(arg)
        {
            $.each(arg, function(index, val) 
            {
                $.post('returnsample.php', { query : val }, function(resp) 
                {
                    // resp = $.parseJSON(resp);
                    if (resp == "YES IT WORKED") 
                    {
                        $('.append-range').append('<strong>Date : </strong>'+val+'<p>Got Right Answer</p><br>');
                    }
                    else
                    {
                        $('.append-range').append('<strong>Date : </strong>'+val+'<p>Got error</p><br>');
                    }
                });
            });
        }
    })
</script>
<body>
    <div class="container">
        <div class="row">
            <h1>Range between two dates:</h1>
        </div>
        <br>
                <div class="row">
            <div class="append-range"></div>
        </div>
    </div>
</body>
</html>

我创建了一个小提琴来演示所需的效果。不过,我已经将您的对象更改为数组,因为它是数字索引的。

脚本所做的是进行 ajax 调用,当触发success时,它将决定要做什么,然后重新启动,遍历整个数组。

u = 0;
function startProcess(arg){
  if(typeof arg[u] !== 'undefined'){
    $.ajax({
      url: "returnsample.php",
      method: 'post',
      query: arg[u],
      success: function(resp){
        if(resp == "YES IT WORKED"){
          $('.append-range').append('<strong>Date : </strong>'+arg[u]+'<p>Got Right Answer</p>')
        }else{
          $('.append-range').append('<strong>Date : </strong>'+arg[u]+'<p>Got error</p>')
        }
        u++;
        startProcess(arg);
      }
    })
  }
}
startProcess(["2016-01-07","2016-01-08","2016-01-09","2016-01-10","2016-01-11","2016-01-12","2016-01-13","2016-01-14","2016-01-15","2016-01-16","2016-01-17","2016-01-18","2016-01-19","2016-01-20","2016-01-21","2016-01-22","2016-01-23","2016-01-24","2016-01-25","2016-01-26","2016-01-27","2016-01-28","2016-01-29","2016-01-30","2016-01-31","2016-02-01","2016-02-02","2016-02-03","2016-02-04","2016-02-05"]);

我希望这有帮助

只是为了给你一个想法。

1.将异步 (ajax( 分离为回调函数

2.从数组中弹出每个项目

jquery在这里使用jQuery.defered提供promise API。

我知道最简单的

方法是回调链。我用直接的javascript举了一个例子,应该给你一个想法。贯穿始终的评论以帮助解释。

// first, don't use an associative array unless you really need it,
// a regular array will be much easier to iterate
var arg = [ "2016-01-07","2016-01-08","2016-01-09","2016-01-10","2016-01-11","2016-01-12","2016-01-13","2016-01-14","2016-01-15","2016-01-16","2016-01-17","2016-01-18","2016-01-19","2016-01-20","2016-01-21","2016-01-22","2016-01-23","2016-01-24","2016-01-25","2016-01-26","2016-01-27","2016-01-28","2016-01-29","2016-01-30","2016-01-31","2016-02-01","2016-02-02","2016-02-03","2016-02-04","2016-02-05" ];
// start off at index 0
next(arg, 0);
function next(arr, index) {
    // set our terminating condition
    if (index >= arr.length) {
        return;
    }
    // we will set up the next iteration by binding our arguments ahead of time
    var nextCallback = next.bind(null, arr, index + 1);
    // call out to your service, with the current value and a function to process the next once completed
    callService(arr[index], nextCallback);
}
function callService(value, next) {
    // call your service here, I am simulating with setTimeout
    // the key here is that we don't call next() until AFTER we have processed our item
    // $.post(.... function (response) {
    setTimeout(function () {
        // simulate a response since timeout won't provide us one
        var response = value;
        // do stuff with your response
        console.log(response);
        // when done, call the next one
        next();
    }, 100);
}