如何等待阿贾克斯成功处理程序执行完毕前另一 [英] How to wait for ajax success handler to finish before executing another

查看:109
本文介绍了如何等待阿贾克斯成功处理程序执行完毕前另一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的javascript以下情形:

I have the following scenario in my javascript:

  1. 在阿贾克斯加载的记录。
  2. 在此基础上记录的返回值,另一个Ajax调用抓住被添加到DOM
  3. HTML表单
  4. 在当前#2完成后,从#1获得的记录,然后加载到#2创建的窗体。
  1. Ajax loads a record.
  2. Based on the return value of that record, another ajax call grabs a html form that is added into the DOM
  3. When #2 is complete, the records that were obtained from #1 are then loaded into the form created in #2.

我现在用的是,这样,当#2完成后,我可以从1号装载的形式值。现在的问题是,是,它出现时的成功处理程序不等待到结束,只有AJAX调用本身。我需要等待#2成功的功能来完成(因为这是建立在DOM的形式)之前,我可以继续使用的值装载形式。

I am using the when so that when #2 is complete, I can load the form values from #1. The problem is, is that it appears that when doesn't wait for the success handler to finish, only the ajax call itself. I need to wait for the success function of #2 to complete (as this is what created the form in the DOM) before I can continue with loading the form with values.

如果我添加报警1 步骤#2,它的工作原理(我猜是因为它正在等待警报被点击,而在当时,成功处理程序已完成。

If I add an alert1 at step #2, it works (which I'm guessing is because it is waiting for the alert to be clicked, and in that time, the success handler has finished.

推荐答案

做这样的事,你的成功使用嵌套函数回调:

Do something like this where you use nested functions in the success callback:

$.ajax({
    url: "somewhere"
    success: function(data1){
        //Use data1 to determine ajax request #2
        $.ajax({
            url: "somewhere else"
            success: function(data2){
                //Do stuff with data1 and data2
             }
         });
      }
});

这篇关于如何等待阿贾克斯成功处理程序执行完毕前另一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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