In short, how do I let alert(1) run first:

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

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

But jquery ajax call seem like run in asynchronous method. So JavaScript will run everything below first, alert(2) to alert(4), then back to the post method, alert(1).

但是jquery ajax调用看起来像是在异步方法中运行。因此,JavaScript将首先运行下面的所有内容,警告(2)警报(4),然后返回post方法,alert(1)。

Certainly I can just put the code in the ajax function, but this make no sense when I have dozens of functions, then I would have to add the code to all functions.

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

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

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

I want to get some json data from an ajax call, and use it later. So is there any smart solution?

我想从ajax调用中获取一些json数据,并在以后使用它。那么有任何智能解决方案吗?

4 个解决方案

#1


2

in jQuery I simply prefer to use $.when and $.then it's easy to do and code is more readable using this.

在jQuery中我只是喜欢使用$ .when和$。然后它很容易做到,代码使用它更具可读性。

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

This code is work in latest version of jQuery 1.9.1

此代码适用于最新版本的jQuery 1.9.1

更多相关文章

  1. Jquery禁用/启用按钮与文本框代码
  2. jQuery.parseJSON()函数详解
  3. 从内部获取函数名称
  4. Jquery 1.9, JS -函数在Chrome中没有定义
  5. 推荐web 前端代码的编辑分享平台——RunJS
  6. 将php jsonencode数组结果显示为ajax成功函数
  7. 想要改进我的jQuery代码,做我想要的,太丑了,IMO
  8. JQuery的一些基本功能代码(CH1&2)
  9. 函数的作用是:显示内联块。如何?

随机推荐

  1. Python有序字典的两个小“惊喜”~~
  2. 学习SQL:MySQL必知必会
  3. 醒醒!Python已经支持中文变量名啦!
  4. Python 幕后解释器:一系列的学习资源
  5. SQL每日一题
  6. 再说相关性分析
  7. SQL今日一题(7):去重
  8. 为什么继承 Python 内置类型会出问题?!
  9. SQL今日一题(2)
  10. SQL今日一题(8)