我的名字是Dan,我不熟悉Javascript,但我想出了一些代码,其中所需的功能是$ .each div.extractedGroup通过$ .ajax发送其.html()并等待$ .each继续下一组之前的响应。
我可能过于复杂了,但我怎么能改变我的代码才能做到这一点?
我试过的是设置一个变量,当ajax调用是beforeSend时为true,成功时为false,成功事件处理程序中的setTimeout函数,我一直试图包装$ .ajax调用使用setTimeout函数但没有成功。 我觉得我过于复杂了,但我似乎无法理解这一点。
javascript:
$('#processGroup').on('click', function(event) {
event.preventDefault();
$('.extractedGroup').each(function(index, el) {
data = $(this).html();
request = $.ajax({
url: 'wait.php',
type: 'POST',
dataType: 'json',
data: {
urlstoparse: data
},
beforeSend: function() {
console.log('sending: ' + data);
//next in $.each should wait until success before next group is processed
},
success: function(res) {
console.log(res);
//next in $.each can now be processed
}
})
.done(function() {
console.log("success");
})
.fail(function(res) {
console.log(res);
})
.always(function() {
console.log("complete");
});
});
});
HTML:
<div id="responseResult" style="">
<div class="extractedGroup">www.pinterest.com/pin/504262489497532154/,www.pinterest.com/pin/355080751843289362/,www.pinterest.com/pin/294704369339289320/,www.pinterest.com/pin/300685712590894312/,</div>
<div class="extractedGroup">www.pinterest.com/pin/555068722796876871/,www.pinterest.com/pin/69805862945258757/,www.pinterest.com/pin/94575660900159173/,www.pinterest.com/pin/521221356846916476/,</div>
<div class="extractedGroup">www.pinterest.com/pin/197173289911047820/,www.pinterest.com/pin/413486809511385544/,www.pinterest.com/pin/355080751843289327/,www.pinterest.com/pin/53691420527287022/,</div>
<div class="extractedGroup">www.pinterest.com/pin/135882113732404986/,www.pinterest.com/pin/464222674063278838/,www.pinterest.com/pin/339318153145966062/,www.pinterest.com/pin/31103053648675435/,</div>
<div class="extractedGroup">www.pinterest.com/pin/414542340674052776/,www.pinterest.com/pin/65583738298561215/,www.pinterest.com/pin/497718196292156699/,www.pinterest.com/pin/101753272800833432/,</div>
<div class="extractedGroup">www.pinterest.com/pin/421157002626993183/,www.pinterest.com/pin/43628690112051613/,www.pinterest.com/pin/414542340674052770/,www.pinterest.com/pin/220957925438000313/,</div>
<div class="extractedGroup">www.pinterest.com/pin/462322717970755136/,</div>
我在这里做错了什么? 任何帮助深表感谢。谢谢!
答案 0 :(得分:0)
感谢jfriend00我了解到没有停顿并等待javascript,让我重写我的代码:
var groups = $('.extractedGroup');
var i = 0;
getData(i, groups);
function getData(i, groups) {
count = groups.length;
if (i < count) {
request = $.ajax({
url: 'wait.php',
type: 'POST',
dataType: 'json',
data: {
urlstoparse: groups.eq(i).html()
},
beforeSend: function() {
console.log('sending: ' + groups.eq(i).html());
},
success: function(res) {
console.log(res);
i = i + 1;
getData(i, groups);
}
})
.done(function() {
console.log("success");
})
.fail(function(res) {
console.log(res);
})
.always(function() {
console.log("complete");
});
}
}