考虑这个代码片段:
$('#selectone').change(function(){
var amount;
$.get('search.php', {search:'units'}, function(result){
//this will return only one or zero for me.
amount = result;
})
if(amount>0)
{
alert('This option has been selected, please select another one');
}
})
我的变量amount
总是未定义
。如何修复或重构这个问题?
最佳答案
这是因为以下代码在您的 $.get()
请求中的回调函数之前运行:
if(amount>0)
{
alert('This option has been selected, please select another one');
}
AJAX 调用是异步的,这意味着它们周围的代码在 AJAX 调用等待响应时运行。因此 if(amount>0)
代码在 AJAX 回调触发之前运行(这意味着对于您的 if/then
语句 amount
将始终等于空
)。
要执行您想要的操作,我建议将该代码放入您的 $.get()
请求的回调函数中:
$('#selectone').change(function(){
$.get('search.php', {search:'units'}, function(result){
//this will return only one or zero for me.
if(result>0)
{
alert('This option has been selected, please select another one');
}
});
});
--更新--
您还可以使用 jQuery 的 $.when()
方法:
$('#selectone').change(function(){
var amount;
var jqXHR = $.get('search.php', {search:'units'}, function(result){
//this will return only one or zero for me.
amount = result;
});
$.when(jqXHR).then(function () {
if(amount>0)
{
alert('This option has been selected, please select another one');
}
});
});
关于jquery - 我需要在 jQuery 中的 get 函数之外使用 var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8273466/