Javascript AJAX响应,用于循环难度

时间:2014-10-23 20:37:07

标签: javascript jquery ajax

我有点问题。也就是说,我想在我的for循环之外得到我的变量:count_green的值。有人知道我该怎么做吗? 以下是我的代码片段:

function State(type, count, list_name){
var count_green = 0;
var count_yellow = 0;
var count_red = 0;

for (i = 0; i < count; i++){
    var jqxhr = $.ajax( "/custom_data/getState/" + type[i]).done(function(result) {
        for (j = 0; j < count; j++){
            if(result.type == type[j]){
                if(result.value == "GREEN"){
                    $("#" + type[j]).css("color","#468847");
                    count_green = count_green + 1;
                }
                if(result.value == "YELLOW"){
                    $("#" + type[j]).css("color","#f89406");
                    count_yellow = count_yellow + 1; 
                }
                if(result.value == "RED"){
                    $("#" + type[j]).css("color","#b94a48");
                    count_red = count_red + 1;
                }
            }
        }
    });
}
    //Here I would need the value of count_green, count_yellow and count_green
    //Unfortunately they are outside of the for loop 0.
    addCounters(count_green, count_yellow, count_red);
}

function addCounters(state_green, state_yellow, state_red){
    $(".line").find(".list").append('<span class="badge pull-left count_badge badge-success">' + state_green + '</span>');
}

正如你可以看到我是否把方法调用:for循环中的addCounters我得到了很多徽章,为什么我需要访问count循环:count循环和count循环之外的count_green,count_yellow和count_red。 我看到了一些带回调的解决方案,但我只需要一次变量的值,如果我使用回调,我会得到超过1倍的值。

提前谢谢。

1 个答案:

答案 0 :(得分:1)

一种解决方案是同步请求。 http://api.jquery.com/jquery.ajax/查看异步属性。

$.ajax( "/custom_data/getState/" + type[i], {async: false}).done(...)

另一种解决方案看起来像这样

var requestCount = 0;

for (i = 0; i < count; i++){
    var jqxhr = $.ajax( "/custom_data/getState/" + type[i]).done(function(result) {
        for (j = 0; j < count; j++){
            if(result.type == type[j]){
                if(result.value == "GREEN"){
                    $("#" + type[j]).css("color","#468847");
                    count_green = count_green + 1;
                }
                if(result.value == "YELLOW"){
                    $("#" + type[j]).css("color","#f89406");
                    count_yellow = count_yellow + 1;
                }
                if(result.value == "RED"){
                    $("#" + type[j]).css("color","#b94a48");
                    count_red = count_red + 1;
                }
            }
        }
        requestFinished(count_green, count_yellow, count_red);
    });
}

function requestFinished(count_green, count_yellow, count_red){
    requestCount++;
    if(requestCount == count){//all requests finished
       addCounters(count_green, count_yellow, count_red);
    }
}