我正在尝试使用 cURL 功能检查某些电子邮件地址是否在网站上注册。
所以在本例中我有 3 个 textarea
元素。第一个包含电子邮件列表,第二个包含实时电子邮件(表明电子邮件已注册),第三个包含未注册的电子邮件。然后有一个名为“检查”的按钮,如果用户单击此按钮,则会发出一个接一个的 AJAX 请求,并一个接一个地显示结果,而不是一次发出多个 AJAX 请求(async: true
)或一个接一个 AJAX 请求,但在请求结束时出现一次结果(async: false
)。
如果我使用async: true
,我的浏览器会因大列表而崩溃,如果我使用async: false
,我不知道我的应用程序是否正在运行或不是因为它在请求结束时显示结果,即使请求是一个接着一个。
然后,为了让我的问题变得简单,这是我的代码。
$("div#check").click(function(){
//Assume i just grab email lists from text area and put in array
var mail_lists_clean = ["a@yahoo.com", "b@aol.com", "c@gmail.com"];
var promises = [];
$.each(mail_lists_clean, function(index, value){
var promise = $.ajax({
method: "POST",
url: "valid_check.php",
//cache: false,
async: false,
data: {
email: value
}
}).success(function(data) {
if (data == "live") {
//append email to second textarea
}
else {
//append email to third textarea
}
});
promises.push(promise);
});
$.when.apply($, promises)done(function() {
alert("All Request done!");
}).fail(function() {
console.log("error");
});
});
谁能帮我依次发出 AJAX 请求并依次显示结果吗?请更正我上面的代码。谢谢。
最佳答案
一一进行ajax调用
您需要在$.ajax
success
回调函数中进行递归调用。
function ProcessEmailList(mail_list) {
// process one email at a time
var value = mail_list.pop();
// if there is email in the array
if (value) {
$.ajax({
method: "POST",
url: "valid_check.php",
async: false,
data: {
email: value
}
}).done(function(data) {
if (data == "live") {
//append email to second textarea
} else {
//append email to third textarea
}
// recursion call, process rest of the email
ProcessEmailList(mail_list);
}).fail(function() {
console.log("error");
});
} else {
// no more email in the array, we have processed all
alert("All Request done!");
}
};
$("div#check").click(function() {
//Assume i just grab email lists from text area and put in array
var mail_lists_clean = ["a@yahoo.com", "b@aol.com", "c@gmail.com"];
ProcessEmailList(mail_lists_clean);
});
关于javascript - 一一循环ajax请求并一一显示结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30773142/