AJAX全局阵列存储


AJAX Global Array Storage

长话短说,我试图将返回AJAX的JSON中的相应数据值存储到这些全局数组中。我知道数组的构造是正确的,因为我已经在AJAX中放置了警报,但当我将其放置在AJAX之外时,数组仍然是未定义的。

我如何导出整个popData JSON对象来处理它并将值存储在全局数组中,或者在AJAX中填充数组以在调用之外执行?我需要这些数组能够被另一个函数访问,以将填充值与用户选择的一小范围的值进行比较——如果有人想建议一种更好的方法,但它必须在HTML中已经完成的加载上提取填充值。我认为这是在服务器上用最少的AJAX调用实现这一点的最简化的方法,但我愿意接受建议!:D

    var popProducers = new Array();
    var popProducersCount = new Array();

    function getPopulationInfo(){
        $.ajax({
            url:phpURL,
            cache:false,
            dataType:"json",
            data: { },
            success:function(popData){
                for (i=0;i<popData.length;i++){
                    //producers and producersCount should be the same length at all times!
                    //If current producer name isn't in array already
                    if(popProducers.indexOf(popData[i].ProducerName) == -1){
                        //add new element to represent new producer quantity (producerCount.length returns number of elements in the array, thus if there are no elements = 0 thus making index 0 equal to 1 and so on)
                        popProducersCount[popProducersCount.length] = 1;
                        //Adds the producer name to the list of producers
                        popProducers[popProducers.length] = popData[i].ProducerName;
                    } else {
                        //Otherwise, it will increment the index of the producersCount array corresponding with the pre-existing producer name's index by 1
                        popProducersCount[popProducers.indexOf(popData[i].ProducerName)] += 1;
                    }

                }
            }
        });
        alert("Population Data Alert: " + popProducers);
默认情况下,

.ajax()及其底层XMLHttpRequest()创建异步请求。这只是意味着,在success处理程序之前会遇到alert()语句。

这里的简单解决方案是,将alert()移动到最底部的success处理程序中。

如果你想以更合适的方式处理它,你可以像一样使用jQuerys Deferred对象

function getPopulationInfo(){
    return $.ajax({
       // lots of stuff
    });
 }

然后称之为

getPopulationInfo().done(function() {
    alert("Population Data Alert: " + popProducers);
});

通过返回CCD_ 8方法,我们隐含地返回了CCD_。长话短说,您可以为success(.done())、error(.fail())和complete(.always())传入一些额外的回调