Javascript在其他函数完成后执行函数 [英] Javascript execute function after other function completes

查看:105
本文介绍了Javascript在其他函数完成后执行函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为save的函数:

I have a function called save:

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时,我想保存执行,并在重定向后发生函数完成。

When the element #preview is clicked, I would like save to execute, and a redirect to happen after the function completes.

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

我已经使用了接受的答案和来自这里的最高评分答案,但都没有成功。重定向发生在函数完成之前。 在另一个函数完成后执行jquery函数

I have used both the accepted answer and the highest rated answer from here, neither are working. The redirect occurs before the function completes. Execute jquery function after another function completes

我也试过:

What I have also tried:

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

我做错了什么?

What am I doing wrong?

推荐答案

在以下方法中,

In context of the following method

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

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

You need to call the callback method which you are passing as argument.

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");
};

这篇关于Javascript在其他函数完成后执行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆