我有一個腳本,它通過 Ajax 將一組數字發送到 Web 服務器。
這些值用于查詢資料庫,然后將表中這些數字的相應值發回,然后我將其發送到我的 html 檔案中的各個 div
見下文。
function getData() {
var faq_get = Array("1", "2", "3");
var faq_async_request = [];
var responses = [];
for (i in faq_get) {
// you can push any aysnc method handler
faq_async_request.push($.ajax({
url: "https://###########.com/data/data.php", // your url
method: "post", // method GET or POST
data: {
mid: faq_get[i]
},
success: function (data) {
console.log("success of ajax response");
responses.push(data);
}
}));
}
$.when.apply(null, faq_async_request).done(function () {
// all done
console.log("all request completed");
console.log(responses);
$("#3").html(responses[2]);
$("#2").html(responses[1]);
$("#1").html(responses[0]);
});
}
下面是 PHP 腳本
$fig = $_POST['mid'];
$sql = "SELECT * from data where id = '$fig'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["scores"];
}
}
我的 Ajax 腳本發送這些資料并接收我想要的回應,但是我有一個小問題。值的位置會不時交換。
請看下面的圖片
uj5u.com熱心網友回復:
您需要在$.when
回呼中處理回應,以便按照它們發送的順序處理它們,而不是在收到回應時處理它們。
function getData() {
var faq_get = Array("1", "2", "3");
var faq_async_request = faq_get.map(id => $.ajax({
url: "https://###########.com/data/data.php", // your url
method: "post", // method GET or POST
data: {
mid: id
}
}));
$.when(...faq_async_request).done(function(...responses) {
// all done
console.log("all request completed");
responses = responses.map(resp => resp[0]); // get the first value from each promise
console.log(responses);
$("#3").html(responses[2]);
$("#2").html(responses[1]);
$("#1").html(responses[0]);
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/434882.html
標籤:javascript php 阿贾克斯 jquery 延迟