【发布时间】:2014-07-09 07:36:01
【问题描述】:
我的名字是 Dan,我对 Javascript 不是很有经验,但我想出了一些代码,其中所需的功能是 $.each div.extractedGroup 通过 $.ajax 发送它的 .html() 并等待$.each 之前的响应继续下一组。
我可能过于复杂了,但我怎样才能改变我的代码来做到这一点?
我尝试设置一个变量,当 ajax 调用为 beforeSend 时为真,成功时为假,成功事件处理程序中的 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>
我在这里做错了什么? 任何帮助深表感谢。谢谢!
【问题讨论】:
-
你可能想用你的数据构造一个对象来做一个 POST 来代替循环节点和发出许多网络请求。我不熟悉您的端点,但通常认为单独发出一堆网络请求是不好的做法。
-
您不能在 javascript 中暂停和等待,因此如果您希望每个 ajax 调用在下一个调用之前完成,则不能像现在这样使用
.each()。相反,您从前一个的成功处理程序启动下一个 ajax 调用,并使用您自己的变量跟踪您在迭代中的位置。 -
非常感谢大家! jfriend00,你有我的解决方案,我不得不换个方式思考,我想出了一个函数并跟踪我在代码中的位置。
标签: javascript ajax each