jQuery链接AJAX回调函数

时间:2022-10-23 20:38:11

I have a centralized ajaxSuccess callback function that should initialize components returned by various AJAX calls around the project, something like this:

我有一个集中的ajaxSuccess回调函数,它应该初始化项目周围各种AJAX调用返回的组件,如下所示:

$(document).ajaxSuccess(function (response, status, xhr) {
    initComponents();
});

So the module-level ajax call could just be like:

所以模块级ajax调用可能就像:

$.ajax({
   url: "whatever",
   success: function(data) {
        // Do some stuff to update the DOM, like:
        $("container").html(data);
   }
});

without the need to perform the init of the eventual components I've in the returned HTML.

无需在返回的HTML中执行我最终组件的初始化。

Now I've this issue: if the local ajax callback function is HUGE, I mean, if it performs a really heavy manulation of the DOM, it happens that the global ajaxSuccess function is fired BEFORE the elements returned by the call are placed in the DOM and available for jQuery.

现在我遇到了这个问题:如果本地ajax回调函数是巨大的,我的意思是,如果它对DOM执行非常繁重的操作,则会发生全局ajaxSuccess函数在调用返回的元素放入之前被触发DOM和jQuery可用。

That's because the callback functions are not chained, just exectuted in sequence (I think).

那是因为回调函数没有链接,只是按顺序排出(我认为)。

There is a way to be sure to perform the global ajaxSuccess after the local success callback function is completed?

在本地成功回调函数完成后,有一种方法可以确保执行全局ajaxSuccess吗?

Or, there is a better way to manage these behaviours?

或者,有更好的方法来管理这些行为?

UPDATE: Doing some logging I'm pretty sure the HTML is in place BEFORE we even entry on the global ajaxSuccess. The issue still remains, anyway, as specific jQuery selectors used in the initComponents() function is not retrieving the elements injected in the DOM.

更新:做一些日志记录我很确定在我们进入全局ajaxSuccess之前HTML已经到位。无论如何,问题仍然存在,因为initComponents()函数中使用的特定jQuery选择器不会检索DOM中注入的元素。

If I perfom the initComponents() inside a setTimeout callback, it is working.... but I don't want to use a timeout...

如果我在setTimeout回调中执行initComponents(),它正在工作....但我不想使用超时...

It's like the updated DOM is not yet queryable when ajaxSuccess fires.

这就像ajaxSuccess触发时更新的DOM还不可查询。

UPDATE 2: False alarm. Actually the update of the html was inside a fadeOut callback function that was making it async in relation of other functions... My fault.

更新2:误报。实际上html的更新是在一个fadeOut回调函数内部,它使其与其他函数的异步...我的错。

1 个解决方案

#1


0  

Try to add the global: true property to the $.ajax object.

尝试将global:true属性添加到$ .ajax对象。

#1


0  

Try to add the global: true property to the $.ajax object.

尝试将global:true属性添加到$ .ajax对象。