2011-10-19 33 views
0

我已经设置了一段代码来检查一个条件,并根据该条件执行ajax调用来获取JSON对象,或继续进行其他形式的处理。处理完后,我会根据if/else语句中处理的数据做一些事情。jQuery - 延迟if/else处理直到“.get”调用完成

但是我遇到了一个问题。代码执行if/else,然后在.get完成处理之前继续执行,因此我的最后一部分代码无法正常工作。有没有办法延迟处理其余代码直到.get完成?

我的代码的结构如下:

if(filename != undefined){ 
    $.get(filename, function(json){ 
    $.each(json, function(data){ 
     // Do stuff with the json 
    }); 
    }, "json"); 
} else { 
    // Do some other processing 
} 

// Do some additional processing based on the results from the if/else statement 
// This bit is getting processed before the .get has finished doing it's thing 
// Therefore there isn't anything for it to act upon 

回答

1

$.get使用async: false选项进行同步请求。 http://api.jquery.com/jQuery.ajax/

注:

@Neal: “这并不总是最好的选择,特别是如果Ajax请求挂起了太久。”

+0

@Kevin - 这并不总是最好的选择。特别是如果ajax请求时间过长。 – Neal

+0

Thx Neal,那是真的。我会将其添加到答案中 – beefyhalo

3

做一个回调函数,而不是针对其他动作:

if(filename != undefined){ 
    $.get(filename, function(json){ 
    $.each(json, function(data){ 
     // Do stuff with the json 
     doTheRest(); 
    }); 
    }, "json"); 
} else { 
    // Do some other processing 
    doTheRest(); 
} 

function doTheRest(){ 

    // Do some additional processing based on the results from the if/else statement 

} 

只记得变量的作用域,如果你有,将参数传递给doTheRest函数。

相关问题