我想从URL加载一些内容,以便在我的代码中使用它。我尝试了闭包和这个:
function getStringFromURL(url) {
var getter = function() {
this.result = "undef";
this.func = function(response) {
this.result = response;
};
};
var x = new getter();
$.get(url, x.func);
return x.result; // the it returns "undef" and not the wanted response
}
什么都不管用。我永远不会得到内容,但是如果我像$.get("http://localhost:9000/x", function(response) { alert(response) });
一样用alert
调用它,它就可以工作了--但是我想保存响应。我认为$.get
-method的作用域有问题。
这有什么问题吗?
发布于 2012-05-28 01:23:55
如果没有服务器提供的显式协议,您无法在标准的get查询中分析从另一个域或端口获得的内容。
阅读这篇文章:https://developer.mozilla.org/en/http_access_control,你会看到如何为你的站点定义合适的头文件,这样浏览器就会知道跨域请求是正常的。
你就有了闭包的问题。如果您想在getter之外的另一个上下文中调用x.func,请尝试这样做:
var getter = function() {
var _this = this;
this.result = "undef";
this.func = function(response) {
_this.result = response;
};
};
编辑:正如其他人所提到的,您不能立即从getStringFromURL
返回x.result。必须在回调中使用该值。实际上,在javascript中围绕异步调用定义同步getter通常是不可能的。
发布于 2012-05-28 01:43:35
$.get是异步方法
您需要将回调函数作为参数传递给getStringFromURL
function getStringFromURL(url, callback) {
var getter = function () {
this.result = "undef";
this.func = function (response) {
this.result = response;
callback(response);
};
};
var x = new getter();
$.get(url, x.func);
}
getStringFromURL("http://localhost:9000/x", function (res) { alert(res) });
如果你想返回结果,这是不可能的。
在JavaScript中你不能混用同步和异步如果你阻塞了脚本,你就阻塞了浏览器。
https://stackoverflow.com/questions/10775862
复制相似问题