如何在循环中进行ajax调用时将数字存储在全局变量中?

时间:2018-01-05 06:33:59

标签: javascript jquery ajax

以下是情景:

( function($) {
    var currentPageUrl = window.location.href;
    var eciDisplayedCategoryCount;
    var eciDisplayCount = false;
    var eciTempCount = 0;
    if(currentPageUrl.indexOf('&page=') !== -1 ){
        var eciPageNum = currentPageUrl.substring(currentPageUrl.indexOf('&page=') + 6);

        if( eciPageNum ) {
            eciPageNum = parseInt(eciPageNum);
            for(i = eciPageNum - 1; i > 0; i--){
                var eciTempURL = currentPageUrl.substring(0, currentPageUrl.indexOf('&page=') + 6) + i;
                if( eciTempURL) {

                    $.get( eciTempURL, function( data ) {
                        // I want to access the eciTempCount
                        eciTempCount += $(data).find('ul.productGrid li.product').length;
                    });
                }
            }

            console.log( eciTempCount );
            // I want to access eciTempCount here but it is resulting to 0 even if the ajax is returning some value.
            if( eciTempCount ) {
                eciDisplayedCategoryCount = eciTempCount + 1;
                console.log( eciDisplayedCategoryCount );
                var eciDisplayCount = true;

            }
        }

    } else {
        var eciDisplayedCategoryCount = $('ul.productGrid li.product').length;
        if( eciDisplayedCategoryCount ){
            var eciDisplayCount = true;
        }

    }
    if( eciDisplayCount ) {
        $("#_eciCnt").html(eciDisplayedCategoryCount);
        $('.eci-product-counter').show(); 
    }   
})(jQuery);

我想在ajax调用之外访问eciTempCount,因为我已在第一个中初始化并在ajax调用内部进行了更改。但变量eciTempCount的值不会更改,结果为0。

0 个答案:

没有答案