2016-09-27 21 views
1

我的代碼是這樣的,我試圖用jQuery函數的結果填充表單域。但它不起作用。我在這裏做錯了什麼?它記錄結果到控制檯罰款,包括散列和數組:如何使用通過jQuery獲得的變量?

jQuery(document).ready(function() { 
    new GetBrowserVersion().get(function(result, components){ 
     console.log(result); //a hash 
     console.log(components); //an array 
    }); 

    var unique_id = result; 

    $('#unique_id').val(unique_id);  
}); 

我所得到的是這樣的:

Uncaught ReferenceError: result is not defined 

其次是哈希和數組。

+0

可能重複[如何從異步調用返回響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an - 異步呼叫) –

回答

5

你正在關閉的功能和值不可用(在範圍內)使用,以更新輸入:

jQuery(document).ready(function() { 
    new GetBrowserVersion().get(function(result, components){ 
     console.log(result); //a hash 
     console.log(components); //an array 

     var unique_id = result; 
     $('#unique_id').val(unique_id); 
    }); 
}); 

順便提及 - 你可以直接在函數中使用的參數,而無需創建的中間變量結果::

jQuery(document).ready(function() { 
    new GetBrowserVersion().get(function(result, components){ 
     console.log(result); //a hash 
     console.log(components); //an array 

     $('#unique_id').val(result); 
    }); 
}); 
+0

Doh!對我來說太愚蠢了。謝謝! :) – user1996496

1

如果你確實需要result其他地方,你可以使用閉包來獲取get()之外的價值。

var result; 

new GetBrowserVersion().get(function(r, components){ 
    console.log(r); //a hash 
    console.log(components); //an array 

    result = r; // assigns to the result in the enclosing scope, using a closure 
}); 

var unique_id = result; 
$('#unique_id').val(unique_id);