1

我想从 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
}

根本没有任何效果。我永远不会得到内容,但如果我用它来调用它- 但我想保存响应alert。我认为-method$.get("http://localhost:9000/x", function(response) { alert(response) });的范围存在问题。$.get

这有什么问题?

4

2 回答 2

3

如果没有服务器给出的明确协议,您无法在标准 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;
     };
 };

编辑:正如其他人所提到的,您不能立即返回 x.result from getStringFromURL。您必须在回调中使用该值。事实上,在 javascript 中围绕异步调用定义同步 getter 是不可能的。

于 2012-05-27T17:23:55.133 回答
1

$.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 中混合同步和异步,即阻止浏览器。

在这里查看JavaScript 中的异步循环

于 2012-05-27T17:43:35.037 回答