2012-05-27 37 views
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$.get("http://localhost:9000/x", function(response) { alert(response) });這樣的內容調用它,它就可以工作 - 但我想保存回覆。我認爲這是$.get-方法的範圍問題。

這是怎麼回事?

回答

3

您無法分析從標準get查詢中的其他域或端口獲取的內容,而無需服務器給出明確的一致性。

閱讀:https://developer.mozilla.org/en/http_access_control 您將看到如何爲您的網站定義正確的標題,以便它說瀏覽器的跨域請求是好的。

而你有關閉問題。如果你想在另一個方面比吸氣調用x.func試試這個:

var getter = function() { 
    var _this = this; 
    this.result = "undef"; 
    this.func = function(response) { 
     _this.result = response; 
    }; 
}; 

編輯:正如其他有mentionned,你不能馬上x.result從getStringFromURL返回。您必須使用回調中的值。實際上,在異步調用中,通常不可能在JavaScript中定義一個同步getter。

+1

爲什麼工作與'alert'的代碼? (''.get(「http:// localhost:9000/x」,function(response){alert(response)});') – Themerius

+1

因爲您可能在您的計算機上本地測試網站。所以它是相同的來源,你可以處理你自己的數據。 – chucktator

+0

有些事情是可能的。像警報一樣,填寫顯示的div,console.log。有些不是。 –

1

$不用彷徨是異步方法

你需要傳遞一個回調函數作爲參數傳遞給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中混合使用同步和異步。

看看這裏Asynchronous for cycle in JavaScript

+0

這不會改變相同原產地政策的問題。 – chucktator

+1

@chucktato這裏的起源策略沒有問題http:// localhost:9000 /是他的網站,/ x是他想要加載的URL,正如他在他的問題中提到的,他沒有說我想加載一些內容從一個域,我有一個問題,因爲當我加載本地主機它的作品。 – Beygi

+0

'alert'從localhost提示正確答案,但是「undef」無論如何都會返回。 – Themerius