Javascript等待外部ajax请求 [英] Javascript wait for extern ajax request
问题描述
我已经基于primefaces数据表做了一个简单的滚动内容加载功能:
I've made a simple scroll content loading feature based on primefaces datatable:
PF('tableWidget').jq.bind("scrollstop", function() {
var t = PF('tableWidget');
if(t.jq.scrollTop() + t.jq.height() >= t.jq.children().height()) {
var rows = t.jq.find('tr'); //save current rows
$.ajaxSetup({async: false}); //ajax set sync
t.paginator.setPage(t.paginator.cfg.page + 1); //framework pagination function with an ajax call inside (and other stuff) to get new rows
rows.prependTo(t.jq.find('tbody')); //AFTER pagination, add old rows
$.ajaxSetup({async: true}); //ajax set async again
}
});
说明:当用户向下滚动到dataTable的底部时,我只使用了分页,但是之前保存了旧行.分页完成后,我再次添加行.这样就实现了基于超酷滚动的加载,其中仅需要从服务器加载新数据,而无需再次加载旧内容.
Explanation: When a user scrolls down to the bottom of the dataTable, I just use the pagination, but save the old rows before. After finishing the pagination, I add the rows again. This leaves to a super cool scroll based loading, where only new data needs to be loaded from the server, and not the old content again.
但是,正如我在其他问题中所读到的那样,使用同步ajax调用是不好的做法.
But as I read in other questions, using synchronized ajax calls is bad practice.
要覆盖"t.paginator.setPage(x)"函数并不容易,因为在此函数中随时都有ajax调用.
It's not easy to override the "t.paginator.setPage(x)" function, because in this function there is anywhere an ajax call.
有没有办法包装整个函数,并向其中添加一些成功回调,而无需深入研究真正的基本ajax调用?
Is there a way, to wrap that whole function, and add some success callback to it, without digging down to the real basic ajax call?
非常感谢!
推荐答案
这是我的解决方案: 因为我需要访问paginator onsuccess或oncomplete方法,所以我现在使用给定的primefaces dataTable ajax侦听器.基于滚动的内容加载系统的整个代码如下:
Here is my solution: Because i needed to get access to paginator onsuccess or oncomplete method i now use the given ajax listener of the primefaces dataTable. The whole code for a scroll based content load system looks like this:
<p:dataTable id="table" value="#{items}" var="item" paginator="true" widgetVar="tableWidget">
<p:ajax event="page" onstart="storeRows()" oncomplete="restoreRows()"/>
...
</p:dataTable>
<h:outputScript>
<!-- variables -->
var rows;
<!-- scroll bottom to load more -->
PF('tableWidget').jq.bind("scrollstop", function() {
var t = PF('tableWidget');
if(t.jq.scrollTop() + t.jq.height() >= t.jq.children().height()) {
t.paginator.setPage(t.paginator.cfg.page + 1);
}
});
<!-- store and restore rows -->
function storeRows() {
var t = PF('tableWidget');
rows = t.jq.find('tr');
}
function restoreRows() {
var t = PF('tableWidget');
rows.prependTo(t.jq.find('tbody'));
}
</h:outputScript>
这篇关于Javascript等待外部ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!