Javascript::在闭包中生成新变量并通过对象实例使用它
啊!我必须从远程文件获取JSON数据,并将其值捕获到我创建的对象“v”的实例可访问的变量中 使用此代码,我得到“未定义” (我正在尽量减少反模式) 我希望我已经说清楚了。 有人能帮我吗Javascript::在闭包中生成新变量并通过对象实例使用它,javascript,json,xmlhttprequest,closures,Javascript,Json,Xmlhttprequest,Closures,啊!我必须从远程文件获取JSON数据,并将其值捕获到我创建的对象“v”的实例可访问的变量中 使用此代码,我得到“未定义” (我正在尽量减少反模式) 我希望我已经说清楚了。 有人能帮我吗 提前感谢。问题在于res.open是异步调用。您不会立即获得数据。执行将到达console.log(“ip”+v.ip)在执行onreadystatechange代码之前。您可以通过插入console.log或使用断点来轻松检查这一点。您需要使用回调重写代码: var Func = function (url)
提前感谢。问题在于
res.open
是异步调用。您不会立即获得数据。执行将到达console.log(“ip”+v.ip)代码>在执行onreadystatechange
代码之前。您可以通过插入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);
});
由于fetch
是异步的,因此在调用函数v.fetch()
后不能立即获取v.ip
的值。要查看该值,必须在回调中输入console.log
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;
console.log(this.ip); // WORKS HERE
}
}
res.send(null);
};
};
var v = new Func("http://ip.jsontest.com/?callback=showMyIP");
v.fetch();
//now I get "undefined" because the function is async and is not done putting the value in this.ip.
console.log("ip " + v.ip);
谢谢你的回答!根据您的建议,脚本似乎在“res.onreadystatechange=function(){…”之前停止执行所以它不会返回控制台。log@ant0nio您不应该发送内部onreadystatechange,也http://ip.jsontest.com/?callback=showMyIP
不返回JSON,而是回调。我更新了我的答案;这几乎有效!console.log中的v.ip变量返回未定义的值。@ant0nio您应该学习如何调试东西。这在onread中ystatechange回调实际上是res
对象,因此您需要保留它,请参见编辑。您好!这很好,但这不是我想在本例中做的。我想做的是从构造函数外部执行console.log。无论如何,谢谢:)
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;
console.log(this.ip); // WORKS HERE
}
}
res.send(null);
};
};
var v = new Func("http://ip.jsontest.com/?callback=showMyIP");
v.fetch();
//now I get "undefined" because the function is async and is not done putting the value in this.ip.
console.log("ip " + v.ip);