web2py: how to detect when an LOAD component has loaded via ajax?

允我心安 提交于 2019-12-25 08:16:00

问题


I'm injecting a component into my web2py page using {{=LOAD(...)}} as described at http://web2py.com/books/default/chapter/29/12/components-and-plugins#LOAD, but I need to fire off some javascript once the component is loaded. Normally if something is loaded via ajax, there is a success callback. How can I set one of this via {{=LOAD(...)}} in web2py?


回答1:


The simplest approach would be to set response.js in the controller of the component:

def mycomponent():
    response.js = 'alert("mycomponent just loaded");'
    return dict()

Alternatively, you could simply include a <script> tag directly in the component itself, which will execute when the component is loaded.

Finally, whenever a web2py Ajax call completes, an ajax:complete event is fired. So, you could set up an event handler and check whether the Ajax response is a component:

  $(document).on('ajax:complete', function(e, xhr, status) {
    if (xhr.getResponseHeader('web2py-component-content')) {
      alert('A component just loaded.');
    }
  });

Note that the presence of the web2py-component-content header indicates that the Ajax response is a component.

The only downside of this last approach is that the event handler will be triggered before the content of the component is added to the DOM, so if the event handler takes long to run, it may noticeably delay the appearance of the component content.



来源:https://stackoverflow.com/questions/40685620/web2py-how-to-detect-when-an-load-component-has-loaded-via-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!