我有一个输入字段。每当输入字段中的文本发生变化时,我都会对 process.php 进行 ajax 调用
我需要处理所有的回复。但有些响应会提前出现,而有些响应会较晚出现,具体取决于输入。所以响应的顺序与ajax调用的顺序不同。
所以现在我通过设置 async: false 来做到这一点
但我不希望客户端因 async: false 而卡住
$("#text_input").on("input", function() {
var password = $("#text_input").val();
var length = password.length;
$.ajax({
url: "process.php",
type: "POST",
async: false,
data: {
password: $(this).val()
}
}).done(function (data) {
console.log(data);
console.log(password + " : " + length);
}).fail(function( jqXHR, textStatus, errorThrown ) {
alert( "Request failed: " + textStatus + " , " + errorThrown );
});
});
我尝试查看promise,但不明白它是否可以应用在这里。
如何按顺序执行响应?
最佳答案
异步的问题正是在于,异步,这意味着代码无需等待完成即可运行。因此,您的所有请求都会发送到服务器,一旦它们开始返回,您的代码就会捕获它们并执行它们。
如果你想按顺序处理它们,你需要构建一个队列和处理该队列的代码。
然后,您应该为所有请求分配一个有序编号,然后该编号应出现在响应中(以便您知道响应的正确顺序)。
然后,您可以将响应添加到队列中,并调用处理队列的方法,但该方法仅按顺序处理队列,这意味着它只处理从 0、1、2、3 等开始的响应。 .所以如果队列中有结果5而不是结果0,则队列不会被处理,只有当结果0存在时才会处理队列,依此类推...
这是一个示例代码,我还没有测试过它,但应该可以工作,或者至少应该让您了解如何开始:)
var currentOrder = 0;
var queue = [];
function processQueue() {
// Sort the queue
queue.sort(function(a, b) {
var aOrder = a.order;
var bOrder = b.order;
if (aOrder < bOrder) {
return -1;
}
if (aOrder > bOrder) {
return 1;
}
// Order is equal (this shouldn't happen)
return 0;
});
if (queue[0].order === currentOrder) {
doSomething(data);
queue.splice(0, 1); // Remove the first item from the queue as it's already processed
currentOrder++;
processQueue(); // Process the queue again
}
}
// Do something with the data
function doSomething(data) {
console.log(data);
}
$('#text_input').on('input', function() {
$.ajax({
url: 'process.php?order=' + order, // We send the order to the backend so it can be returned in the response
type: 'POST',
data: {
password: $(this).val()
}
}).done(function(data) {
// Data should contain the order somewhere, let's say for example it's a json and it's inside data.order
queue.push(data);
processQueue();
});
});
关于javascript - 如何按顺序执行 jQuery AJAX 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44775914/