我的应用程序中有两个javascript/jquery函数,总是有refresh()函数,它从数据库中抓取数据并重新绘制前端视图。
方法之一是将数据发送到PHP函数,这使得简单的插入MySQL数据库,第二次编辑它,在这里(他们是相同的,所以我只发布一个):
function insertedit()
{
$('.res').each(function()
{
$.post("/controller/method/",{id: id},function(data,status,xhr)
{
if(status=="success")
{
}
})
});
refresh();
}
当我试图用这个函数插入数据时,一切工作正常,我的视图正在异步重绘,但是当我试图用它编辑数据时-我必须刷新页面才能看到更新的视图。我认为,编辑操作需要更多的时间比插入和我的刷新功能,它从SQL抓取数据只是抓取旧数据(未删除的记录)-我怎么能修复它?
编辑
$(function()
{
refresh();
});
function insertedit(){
var $promises = [];
$('.res').each(function()
{
$promises.push(
$.post("/controller/metgod/",{id, id},function(data,status,xhr)
{
if(status=="success")
{
}
})
);
});
$.when.apply($, $promises).then(function() {
refresh();
});
}
使用承诺
function insertedit()
{
var $promises = [];
$('.res').each(function(id){
var $this = $(this);
$promises.push(
$.post("/controller/method/", {'id': $this.attr('id')}, function(data,status,xhr){
$this.text(data); // success
})
);
});
$.when.apply($, $promises).then(function(){
refresh();
});
}
看到这里的提琴,它的工作http://jsfiddle.net/69eMp/4/
我在某些时候使用过这样的解决方案,下面是我的解决方案(这里有一个现场演示):
/**
* Class that will handle delayed function calls
* @param fn the funciton to call
* @param ctx the context to use as 'this' inside the function
* @param delay delay in millis
*/
var AsyncCall= function(fn, ctx, delay) {
var timer = null;
ctx = ctx || window;
delay = delay || 1;
return function() {
// prevent calling the delayed function multiple times
if (timer) clearTimeout(timer);
var args = arguments;
timer = setTimeout(function() {
timer = null;
fn.apply(ctx, args);
}, delay);
};
};
// wrap the 'refresh' funciton inside the async call object with a 200 millis delay
var refreshAsync = new AsyncCall(refresh, null, 200);
function insertedit()
{
$('.res').each(function()
{
$.post("/controller/method/",{id: id},function(data,status,xhr)
{
if(status=="success")
{
}
// schedule calling 'refresh'
refreshAsync();
})
});
}
首选的原因是您不必刷新每个Ajax请求。这样,与每次刷新相比,它只执行refresh
函数的次数更少。200毫秒不是很长,但足以让Ajax调用返回,并且不会被用户注意到。