简体   繁体   English

javascript: XMLHttpRequest for json 超出范围

[英]javascript: XMLHttpRequest for json outside the scope

So i was trying to get json data and storing it in a variable.所以我试图获取json数据并将其存储在一个变量中。 The problem is that everything inside the .onReadyStateChange block is like a blackhole, nothing gets out of there so I can't retrieve information.问题是 .onReadyStateChange 块中的所有内容都像一个黑洞,没有任何东西从那里出来,所以我无法检索信息。 I can call functions from within that block and it will work, but anything i try to save to an outside entity will result in null, even if that variable is of the window scope.我可以从该块中调用函数并且它会起作用,但是我尝试保存到外部实体的任何内容都将导致 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

So my question is, is there any way to save that information outside of that block?所以我的问题是,有没有办法将这些信息保存在该块之外? Thanks.谢谢。

Your console.log call is synchronous while the assignment to globalVar was done asynchronously, hence null was printed first even before the assignment resolved.您的console.log调用是同步的,而globalVar的分配是异步完成的,因此即使在分配解决之前首先打印null

==edit== ==编辑==

You may choose to wrap the XMLHttpRequest object inside a Promise:您可以选择将 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);
});

First, you need to know the principle of the ajax.首先需要了解ajax的原理。 you konw, the ajax is an async function, so when you haven't gotten the return value, 'console.log(globalVar)' has been executed.你知道,ajax 是一个异步函数,所以当你没有得到返回值时,'console.log(globalVar)' 已经被执行了。 So you should write in the way:所以你应该这样写:

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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM