我有一個Ajax JQuery腳本,應該發佈一個日期數組到一個PHP頁面獲取結果,如果它是正確的結果,它會在頁面上的div中顯示成功消息,如果它不是正確的返回的結果,它顯示一個錯誤。應該發生的是每個日期應該一次發送1次,等待響應後再轉到下一個日期。該腳本似乎工作正常,但我注意到日期是隨機順序返回。經過調查,我瞭解到這是因爲Ajax調用同時發送多個請求。我想這就是爲什麼它被稱爲異步JavaScript和XML(LOL)。無論如何,我一直在這個小時,似乎無法找到或理解解決這個問題的方法。我已經閱讀了一些關於Javascript承諾和各種東西的東西,但我不明白。如果有人可以幫助一些代碼的幫助,這將是超級讚賞!如何使用Ajax一次只發佈一個數組的值,並在繼續之前等待響應?
下面是完整的HTML文件與Javascript和Ajax調用包括:
<!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>
也許不通過陣列使用每個循環,但通過它和遞增值,當你得到你想要的結果,只有增加而遞增。 –
爲什麼你不發送完整的數組,處理每個日期,然後發回一組結果?看起來像一個更健全的UX – DelightedD0D