2016-04-22 34 views
0

創建的數組,我需要在代碼中稍後引用函數中的線索。我如何在.git方法之外引用線索?我需要引用一個使用.get()

$.get("clues.txt", function(data) 
{ 
    var clues = data.split(','); 
}); 
+0

將線索聲明爲全局變量。 –

+0

請注意'$ .get()'是**異步**操作。當HTTP請求完成*時,回調函數被調用*。可以安排響應數據在回調之外訪問,但不能立即提供。 – Pointy

+0

@DharaParmar - 使它成爲全球是一個壞主意,不建議。 – jfriend00

回答

0

不能可靠地訪問clues其中提供了其價值的特定回調之外。因爲結果是通過異步操作獲得的,所以完成該異步操作的時間是未知的。因此,唯一能夠可靠地使用結果的地方是在回調本身內部或在該回調中調用的函數中,並將值傳遞給該函數。這就是你如何做異步編程。您在此回調中繼續編程序列。

$.get("clues.txt", function(data) { 
    var clues = data.split(','); 
    // other code goes here that uses the `clues` variable 
}); 

// code here cannot use the `clues` variable because the asynchronous operation 
// has not yet completed so the value is not yet available 

這裏有一些其他的相關答案:

How do I get a variable to exist outside of this node.js code block?

Node.JS How to set a variable outside the current scope

How to capture the 'code' value into a variable?

0

爲每Store ajax result in jQuery variable參考。您可以將您的響應數據傳遞給一些更多功能。此外,您還可以通過將您的回覆存儲在您的某個hiddenHTML輸入標記中進行操作。

<input type="hidden" id="clues_data" value=""> 

所以,在你.get()方法,你可以做這樣的事情:

$.get("clues.txt", function(data) 
{ 
    $("#clues_data").val(data); 
}); 

,然後在另外一些功能,你可以訪問它想:

function someFurtherFunction(){ 
    var clues = $("#clues_data").val().split(','); 
    // do something with clues 
} 

我知道這並不是你的問題的確切解決方案,但我試圖幫助你處理這種情況。它可能有助於其他編碼器:)