gpt4 book ai didi

javascript - Jquery 每个在 ajax $.post 之后都不继续

转载 作者:行者123 更新时间:2023-11-28 00:58:13 24 4
gpt4 key购买 nike

我的 jQuery every 似乎都在停止,直到 ajax 请求加载为止。我认为 ajax 是异步的,这里有什么问题?

代码:

$('div').each(function(){

if($(this).attr('id')){
var that = this;
$.post('application/views/dashboard/dashboard.php?component='+$(this).attr('id')+"&settingid="+settingId, function(response){
$(that).html(response);
$(window).trigger('resize');
});
settingId++;
}
});

最佳答案

$.when 将等待所有异步调用完成(顺序和时间不重要),然后可以在最后执行单个额外操作(除了各个操作之外)。您将需要使用 $.ajax 而不是更简单的 $.post:

var requests = [];
$('div').each(function () {
if ($(this).attr('id')) {
var that = this;
requests.push($.ajax({
url: 'application/views/dashboard/dashboard.php?component=' + $(this).attr('id') + "&settingid=" + settingId,
type: "post",
success: function (response) {
$(that).html(response);
}
}));
});
settingId++;
});
$when(requests).then(function () {
$(window).trigger('resize');
});

$.when 的工作原理是获取一组 jQuery promise (在本例中为 ajax promise )并等待它们全部成功。

对上述代码中的任何拼写错误表示歉意。我刚刚写的是直接进入答案:)

您当然可以从此简化代码:

$('div').each(function () {
if ($(this).attr('id')) {

对此:

$('div[id]').each(function () {

关于javascript - Jquery 每个在 ajax $.post 之后都不继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25972983/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com