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
}

何も機能しませんでした。コンテンツを取得することはできませんが、alertlike$.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 で同期ゲッターを定義することは、より一般的には不可能です。

于 2012-05-27T17:23:55.133 に答える
1

$.get は Async メソッドです

コールバック関数を引数として 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 に答える