这是因为下面的代码回调函数之前运行在您的$.get()
要求:
if(amount>0)
{
alert('This option has been selected, please select another one');
}
AJAX调用是异步的,这意味着他们周围的代码运行的AJAX调用等待响应。因此if(amount>0)
代码在AJAX回调触发之前运行(意味着您的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');
}
});
});
--Update--
您还可以使用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');
}
});
});
这可能会帮助:http://stackoverflow.com/questions/6920445/place-ajax-get-into-a-javascript-variable –