web2py:如何检测 LOAD 组件何时通过 ajax 加载? [英] web2py: how to detect when an LOAD component has loaded via ajax?
问题描述
我正在使用 {{=LOAD(...)}}
将一个组件注入到我的 web2py 页面中,如 http://web2py.com/books/default/chapter/29/12/components-and-plugins#LOAD,但我需要在组件加载后触发一些 javascript.通常,如果通过 ajax 加载某些内容,则会出现成功回调.如何在 web2py 中通过 {{=LOAD(...)}}
设置其中之一?
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?
推荐答案
最简单的方法是在组件的控制器中设置 response.js
:
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.
最后,每当 web2py Ajax 调用完成时,都会触发 ajax:complete
事件.因此,您可以设置一个事件处理程序并检查 Ajax 响应是否是一个组件:
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.');
}
});
请注意,web2py-component-content
标头的存在表明 Ajax 响应是一个组件.
Note that the presence of the web2py-component-content
header indicates that the Ajax response is a component.
最后一种方法的唯一缺点是事件处理程序将在 组件的内容添加到 DOM 之前被触发,因此如果事件处理程序需要很长时间运行,它可能会很明显延迟组件内容的出现.
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.
这篇关于web2py:如何检测 LOAD 组件何时通过 ajax 加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!