2016-09-27 9 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) -asynchronous-call) –

答えて

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); 
関連する問題