微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

告诉javascript首先运行jquery ajax

简而言之,如何让alert(1)首先运行:

    $.post('example.PHP', function() {
        alert(1);
    })
    alert(2);
    alert(3);
    alert(4);

但是jquery ajax调用似乎是在异步方法中运行.因此,JavaScript将首先运行下面的所有内容,alert(2)到alert(4),然后再返回post方法alert(1).

当然,我可以将代码放在ajax函数中,但是当我有数十个函数时,这没有任何意义,那么我必须将代码添加到所有函数中.

    $.post('example.PHP', function() {
        alert(1);
        example();
    })

    function example() {
        alert(2);
        alert(3);
        alert(4);
    }

我想从ajax调用获取一些json数据,并在以后使用.那么,有什么聪明的解决方案吗?

解决方法:

在jQuery中,我只是更喜欢使用$.when和$.then,这很容易做到,并且使用此代码可读性更高.

function CatchTheFish(){
console.log('we are catching the fish');
}
function EattheFish(){
console.log('Now time to eat this fish');
}
$.when ( CatchTheFish() ).then( EattheFish() );

代码在jQuery 1.9.1的最新版本中有效

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐