【问题标题】:Javascript execute function after other function completes其他功能完成后的Javascript执行功能
【发布时间】: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


【解决方案1】:

在以下方法的上下文中

$('body').on('click','#preview',function(){
    save(function(){
        window.open('/article/preview/<?php echo $article_id; ?>','_blank');
    });
});

您需要调用作为参数传递的回调方法

function save(callback){
    $.post(url,function(d){

        $('#saving').hide();
        if (d.suc == 1) {
            $('#saved').show();
            setTimeout(function () {
                $('#saved').hide();

                //CALL THE METHOD
                callback();  
            }, 2000);
        } else {
            $('#save_err').html(d.err).show();
        }
   },"JSON");
};

【讨论】:

    【解决方案2】:

    你永远不会调用回调函数,所以它永远不会重定向。您需要在超时结束时调用它:

    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();
                    callback();  // <---- call callback
                }, 2000);
            } else {
                $('#save_err').html(d.err).show();
            }
        }, "JSON");
    };
    

    【讨论】:

      猜你喜欢
      • 2012-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多