【问题标题】:javascript: XMLHttpRequest for json outside the scopejavascript:适用于范围之外的 json 的 XMLHttpRequest
【发布时间】:2017-06-25 13:44:46
【问题描述】:

所以我试图获取 json 数据并将其存储在一个变量中。问题是 .onReadyStateChange 块内的所有内容都像一个黑洞,没有任何东西可以从那里出来,所以我无法检索信息。我可以从该块中调用函数并且它会起作用,但是我尝试保存到外部实体的任何内容都会导致 null,即使该变量属于窗口范围。

var globalVar;

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var foodsArray = JSON.parse(this.responseText);
        globalVar = JSON.stringify(foodsArray);
    }
}

console.log(globalVar);
//result will be null, so will foodsArray had I made it global

所以我的问题是,有没有办法将这些信息保存在该块之外?谢谢。

【问题讨论】:

标签: javascript json scope xmlhttprequest


【解决方案1】:

首先,你需要了解ajax的原理。你知道,ajax 是一个异步函数,所以当你没有得到返回值时,'console.log(globalVar)' 已经被执行了。所以你应该这样写:

var globalVar;

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var foodsArray = JSON.parse(this.responseText);
        globalVar = JSON.stringify(foodsArray);
        console.log(globalVar); // you can get the result
    }
}

【讨论】:

  • 我明白了,但我的目标是获取 json 数据,然后将其保存在窗口范围内的某个数据结构中,以便以后可以在我的 Web 应用程序中随时访问该数据,以便我不需要每次需要数据时都提出休息请求
【解决方案2】:

您的console.log 调用是同步的,而对globalVar 的分配是异步完成的,因此null 甚至在分配解决之前就被首先打印。

==编辑==

您可以选择将 XMLHttpRequest 对象包装在 Promise 中:

var prom = new Promise(function(resolve,reject) {
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            resolve(this.responseText);
        }
    }
});

prom.then(function(foodsArray) {
    console.log(foodsArray);
});

【讨论】:

    猜你喜欢
    • 2015-12-09
    • 2015-01-31
    • 2014-10-15
    • 2014-11-26
    • 2020-10-08
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    相关资源
    最近更新 更多