访问变量“外部”在javascript中的回调函数 [英] access to a variable "outside" of a callback function in javascript

查看:99
本文介绍了访问变量“外部”在javascript中的回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

loadJSON(path, callback) {
    console.log("path: " + path); 
    var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
    xobj.open('GET', path, true);
    xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 && xobj.status == "200") {
            callback(xobj.responseText);
          }
    };
    xobj.send(null);  
 }

上面是一个在本地访问json文件的函数。
然后从`foobar()'解析检索到的数据。
但是从回调函数的外部,无法访问变量json。
我搜索了类似的SO问题和异步概念,但仍然无法找到解决问题的方法。

Above is a function to access a json file locally. Then from `foobar()' parse the data retrieved. However from "outside" of call back function, the variable "json" cannot be accessed. I had searched similar SO questions and async concepts but still was not able to figure a way to resolve it.

function foobar() { 
    var json;
    loadJSON("data.json", function(response) {
        json = JSON.parse(response);
        console.log(json[0].name); // Successfully shows the result
    });
    console.log(json[0].name); // TypeError: json is undefined
}

有没有办法访问变量在回调之外?

Is there a way to access the variable "outside" of the callback?

推荐答案

这是因为它设置为异步模式。

It's because it's set in Asynchronous mode.

console.log(json[0].name); // TypeError: json is undefined

此代码在json填充之前执行。因此,当您尝试访问它时,它可能仍然是空的。此行中的第三个参数将其定义为Async:

This code is executed before json is filled. Therefore when you try to access it, it might be still empty. The third argument in this line defines it as Async:

xobj.open('GET', path, true);

你可以尝试把

xobj.open('GET', path, false);

但它不再是异步的,用户必须等待请求结束,所以当回调方法已被调用而不是之前,确保使用'json'var可能更好。保持异步模式。
为此,您需要重新构建代码。

But it isn't asynchronous anymore and the user will have to wait for the request to end, so it's probably better to make sure to use the 'json' var when the callback method has ben called and not before. Keeping the asynchrnous mode on. For this you'll need to restructure your code.

Gerardo Furtado发布的链接完全准确,您应该查看。

The link posted by Gerardo Furtado is totally accurate, you should check it.

编辑: 正如我已经说过的,和其他用户一样,async:false也不是很好,所以我正在编辑我的答案:

As i already stated, and other users too, the async:false is not very good, so i'm editing my answer:

function foobar() { 
    var json;
    loadJSON("data.json", function(response) {
        json = JSON.parse(response);
        // Call another function with json that is now filled with data
        triggered(json);
    });
}

function triggered(json) {
    console.log(json[0].name);
    // Do your work on json
}

这篇关于访问变量“外部”在javascript中的回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆