【发布时间】:2015-06-02 20:32:04
【问题描述】:
我有一个叫做保存的函数:
function save(callback){
var ed=tinyMCE.get('body');
var data=ed.getContent();
$('#saving').show();
$('#save_err').hide();
$.post('/article/ajax/save',{title:$('#title').val(),body:data,token:token,aid:<?php echo $article_id; ?>},function(d){
$('#saving').hide();
if(d.suc==1){
$('#saved').show();
setTimeout(function(){$('#saved').hide()},2000);
}else{
$('#save_err').html(d.err).show();
}
return true;
},"JSON");
};
当点击元素#preview 时,我希望保存执行,并在函数完成后进行重定向。
$('body').on('click','#preview',function(){
save(function(){
window.open('/article/preview/<?php echo $article_id; ?>','_blank');
});
});
我已经使用了此处接受的答案和评分最高的答案,但都不起作用。重定向发生在函数完成之前。 Execute jquery function after another function completes
我也尝试过:
$('body').on('click','#preview',function(){
$.when(save()).done(function(){
window.open('/article/preview/<?php echo $article_id; ?>','_blank');
});
});
我做错了什么?
【问题讨论】:
-
$.when仅适用于返回承诺的函数。 (然后是不必要的) -
您认为
save函数的“完成”究竟是什么? ajax请求什么时候加载?#saved动画什么时候完成? -
您创建了参数回调,但没有使用它。它必须在哪里调用?
标签: javascript jquery ajax function