请考虑以下代码段:
$('#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
总是来undefined
。如何修复或重构?
答案 0 :(得分:7)
这是因为以下代码在$.get()
请求中的回调函数之前运行:
if(amount>0)
{
alert('This option has been selected, please select another one');
}
AJAX调用是异步的,这意味着它们周围的代码在AJAX调用等待响应时运行。因此,在AJAX回调触发之前if(amount>0)
代码正在运行(这意味着if/then
语句amount
始终等于null
。)
要做你想做的事情我建议把这些代码放在你的$.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');
}
});
});
答案 1 :(得分:0)
你不能只在成功函数中使用它吗?这将是最好的方式:
$('#selectone').change(function(){
var amount;
$.post({
async : false, // this makes it possible
url: 'search.php',
data: {search:'units'},
success : 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');
}
})