哈!我必须从远程文件中获取 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/