Javascript 延迟后续ajax调用,直到第一个ajax调用完成

Javascript 延迟后续ajax调用,直到第一个ajax调用完成,javascript,jquery,Javascript,Jquery,我在javascript事件的计时方面遇到了一些问题。我遇到的问题是,代码的一部分似乎在另一部分完成之前执行。我需要确保第一个代码在后一个代码开始之前完成。以下是初始代码: function(){ myLoop(); //this needs to complete before the call to myMethod below $.ajax({ url: sURL + "myController/myMethod", success: func

我在javascript事件的计时方面遇到了一些问题。我遇到的问题是,代码的一部分似乎在另一部分完成之前执行。我需要确保第一个代码在后一个代码开始之前完成。以下是初始代码:

function(){     
    myLoop();  //this needs to complete before the call to myMethod below 
    $.ajax({
    url: sURL + "myController/myMethod",
    success: function() {       
    $.msg("My Success Message",{live:10000});
    error: function(){
    $.msg("My Error Message",{live:10000});
});
}
下面是循环并将记录插入数据库的代码:

function myLoop(){
$('input[name=c_maybe].c_box').each(function(){
if( $(this).prop('checked') ){ 
    var rn = $(this).prop('value'); 
    $.ajax({
        url: sURL + 'myController/myInsert',
        type:"POST",
        dataType: 'text',
        data: {'rn': rn},
        success: function(data) {
            //not sure what to do on success.
        }
    });
} 
}); 
} 
似乎正在发生的问题是对
myController\myMethod
的调用发生在
myLoop
完成将所有记录插入数据库之前

有人能给我建议一种重新设计代码的方法,这样我就可以确保在
myLoop
完全完成之前不会调用
myController\myMethod


谢谢。

您可以使用添加到jQuery中的$.when函数

事情是这样的:

   $.when(ajaxFunction1(), ajaxFunction1()).done(function(response1, response2){
    // when the function calls are done this code here will be executed -> the response will be passed as parameters corresponding to the functions -> response1, response2
   });
或者,您可以尝试在ajax函数中使用“beforeSend”:

$.ajax({
   beforeSend: function(){    
     alert("doing stuff before the ajax call ...");    
   },
   success: function(){    
    alert("Whoa!");    
   }
 });

$。when.apply
用于调用ajax请求数组上的
$。when
时,在所有请求完成之前不会调用
.done

您可以使ajax调用同步。这样,执行将被阻止,直到ajax调用返回:

$.ajax({
    url: sURL + 'myController/myInsert',
    type:"POST",
    dataType: 'text',
    data: {'rn': rn},
    async: false,
    success: function(data) {
        //not sure what to do on success.
    }
});

很酷。我不知道jQuery的这个特性。起初我以为这是一个“简单”的回访问题。没那么多。你具体说的是哪一个功能?
-我看到它是在jQuery 1.5中添加的。我看了很多关于jQuery的问题。我很惊讶我以前没有遇到过。你的beforeSend解决方案看起来比其他答案更干净+感谢您的评论。这让我走上了正确的道路,但我的循环代码仍然存在间歇性故障。关于这一点,我已经发布了另一个问题。我很高兴我能提供帮助:)如果你认为这是你所需要的,请随意接受答案:PPP
$.ajax({
    url: sURL + 'myController/myInsert',
    type:"POST",
    dataType: 'text',
    data: {'rn': rn},
    async: false,
    success: function(data) {
        //not sure what to do on success.
    }
});