【问题标题】:AJAX Global Array StorageAJAX 全局阵列存储
【发布时间】:2012-07-28 11:07:08
【问题描述】:

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

如何导出整个 popData JSON 对象以对其进行处理并将值存储在全局数组中,或者在 AJAX 中填充数组以在调用之外进行?我需要另一个函数可以访问这些数组,以将总体值与用户选择的窄范围值进行比较——如果有人想提出更好的方法,但它必须在 onLoad 上提取总体值已经在 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);

【问题讨论】:

    标签: php javascript ajax arrays global


    【解决方案1】:

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

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

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

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

    然后像这样称呼它

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

    通过返回.ajax() 方法,我们隐式返回Deferred object。长话短说,您可以为success (.done())、error (.fail()) 和complete (.always()) 传递一些额外的回调

    【讨论】:

    • 奇怪的是,当我将警报移到另一个函数中时,它起作用了。所以因为 AJAX 是异步的,所以在数组实际填充之前就调用了 alert()?
    • 然后,我怎样才能让脚本等到调用完成?必须有一些选项或参数可以促进这一点,不是吗?
    • @superspartan999:您确实可以通过向.ajax() 添加一个附加属性来强制请求同步,即async: false。但是,jQuery 1.8 已弃用此方法,并且这样做非常糟糕。它会冻结并锁定浏览器 UI,直到请求完成。因此,它是一个更好、更清洁的解决方案,可以处理上述回调。
    • 不客气,伙计,我真的希望你还是选择了回调解决方案:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 2015-05-10
    • 2015-08-08
    • 2018-02-04
    • 2011-04-12
    相关资源
    最近更新 更多