【问题标题】:How to access an array outside onreadystatechange (scope issue)如何访问 onreadystatechange 之外的数组(范围问题)
【发布时间】:2016-11-16 13:40:46
【问题描述】:

我有一个函数 ajaxCall(),它调用一个带有数组的 json 文档。 我从 xmlhttp.responseText 返回的数据存储在数组 arrayImages 中。我需要访问函数 ajaxCall() 之外的数组 arrayImages,因为我需要该数组的长度 arrayImages.length。

function ajaxCall(){
    xmlhttp.onreadystatechange = function(){

        if(xmlhttp.readyState==4 && xmlhttp.status==200){
            arrayImages = JSON.parse(xmlhttp.responseText);
            output(arrayImages);

        } 
    }

    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

我在函数中需要这样的东西

var arrayLength = arrayImages.length;

【问题讨论】:

  • 不是范围问题,而是时机问题。您的 XHR 是异步的,只有在 HTTP 请求进行时才会调用状态更改回调。

标签: javascript arrays ajax scope xmlhttprequest


【解决方案1】:

由于onreadystatechange 是一个异步函数,您无法确定它何时会返回您的数组。因此,处理它的唯一方法是使用回调函数在完成时输出数组的length。 像这样:

function ajaxCall(){
    xmlhttp.onreadystatechange = function(){

        if(xmlhttp.readyState==4 && xmlhttp.status==200){
            arrayImages = JSON.parse(xmlhttp.responseText);
            output(arrayImages);

        } 
    }

    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

function output(array)
{
   //your other stuff here
   var arrayLength = array.length;
}

【讨论】:

    猜你喜欢
    • 2016-08-04
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多