2016-09-27 52 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);