Javascript::在闭包中生成新变量并通过对象实例使用它

标签 javascript json xmlhttprequest closures

哈!我必须从远程文件中获取 JSON 数据,并将其值抓取到可由我创建的对象实例“v”访问的变量中。

使用这段代码我得到“未定义”

(我正在尝试尽可能减少反模式)

var Func = function (url) {

    this.url = url;
};

Func.prototype.fetch = function () {

    // fetching the JSON content
    var res = new XMLHttpRequest();
    res.open('GET', this.url, true);
    res.onreadystatechange = function () {

        if (res.readyState == 4) {
            if (res.status == 200) {

                // this is the object I want access from outside
                var obj = JSON.parse(res.responseText);
                this.ip = obj.ip;
            }
        }
        res.send(null);
    };
};

var v = new Func("http://ip.jsontest.com/?callback=showMyIP");
v.fetch();

//now I get "undefined"
console.log("ip " + v.ip);

我希望我已经说清楚了。 有人可以帮我解决这个问题吗?

提前致谢。

最佳答案

问题是 res.open 是异步调用。您不会立即获得数据。在执行 onreadystatechange 代码之前,执行将到达 console.log("ip "+ v.ip);。您可以通过插入 console.log 或使用断点轻松检查这一点。您需要使用回调重写代码:

var Func = function (url) {

    this.url = url;
};

Func.prototype.fetch = function (onready) {

    // fetching the JSON content
    var res = new XMLHttpRequest();
    res.open('GET', this.url, true);
    var that = this;
    res.onreadystatechange = function () {
        if (res.readyState == 4) {
            if (res.status == 200) {

                // this is the object I want access from outside
                var obj = JSON.parse(res.responseText);
                that.ip = obj.ip;
                onready();
            }
        }            
    };
    res.send(null);
};

var v = new Func("http://ip.jsontest.com/");
v.fetch(function () {
    console.log("ip " + v.ip);
});

关于Javascript::在闭包中生成新变量并通过对象实例使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23253236/

相关文章:

android - 将json插入mysql

java - 如何让XMLHttpRequest在IE中不缓存

node.js - 为什么 Restful 不能将 body 传递到数据库中

ajax - 浏览器无法区分通过 AJAX 获得的部分 HTML 和完整页面

javascript - 使用 Node 创建文件并使用提示输入替换变量

javascript - 如果没有页面刷新,单击功能不会触发

javascript - 在 AngularJS 中如何从一个 Controller 重定向到另一个 Controller ?

javascript onclick 触发按键点击(使用jQuery)

php - 导入任何 custom.js 文件时 JSON 提要中断

javascript - 我如何将 Json 数据发布到我的状态 ReactJs 中