我有一些代码来划分部分的单词字符串,并做一个请求(foreach部分)php获得结果并将它们放在元素中。当我使用async: false时,所有工作都很好,但我希望它是async: true。我对async: true的问题是,结果是"随机的",因为请求没有顺序…我已经阅读并搜索了如何解决这个问题,但找不到它…
下面是我的代码:
$(function() {
$("#check").on( "click", function() {
$("#results").empty();
var text = $("#original").val();
var totalWords = text.split(' ').length;
var start = 0;
var numberResults = 10;
var divide = totalWords / numberResults;
var numberOfTimes = Math.floor(divide) + 1;
var test = 0;
for(var index = 0; test < totalWords; index+=10){
var part = text.split(/'s+/).slice((test),(test + 10)).join(" ");
$.ajax({
url: "requests.php",
async : true,
cache: false,
type: "POST",
data: {words : part},
success: function(html){
$("#results").append(html);
$("#check").hide();
}
});
console.log(test);
test = test + 10;
$(".progress-bar").attr("aria-valuenow", test);
$(".progress-bar").css({"min-width" : test + "em"});
$(".progress-bar").css({"width" : test + "%"});
$(".progress-bar").text(test + "%");
console.log(part);
}
});
});
异步执行不能保证执行顺序。因此得名。如果您想要同步,请使用async: false
。jQuery文档
或者,如果你想获得异步执行的优势,比如速度,你可以使用一个解决方案来重新排列数据,或者使用一些额外的参数来按照你需要的顺序定位数据。
一个这样的实现逻辑的例子是:
$(function() {
$("#check").on("click", function() {
$("#results").empty();
var text = $("#original").val();
var totalWords = text.split(' ').length;
var start = 0;
var numberResults = 10;
var divide = totalWords / numberResults;
var numberOfTimes = Math.floor(divide) + 1;
var test = 0;
function action_task(index, data) {
$.ajax({
url: "requests.php",
async: true,
cache: false,
type: "POST",
data: data,
success: function(html) {
//add data at reserved spot
$("#id_" + index).html(html);
$("#check").hide();
}
});
}
for (var index = 0; test < totalWords; index += 10) {
var part = text.split(/'s+/).slice((test), (test + 10)).join(" ");
//reserving a spot
$("#results").append("<span id='id_" + index + "'></span>");
action_task(index, {
words: part
});
console.log(test);
test = test + 10;
$(".progress-bar").attr("aria-valuenow", test);
$(".progress-bar").css({
"min-width": test + "em"
});
$(".progress-bar").css({
"width": test + "%"
});
$(".progress-bar").text(test + "%");
console.log(part);
}
});
});