這是因爲下面的代碼回調函數之前運行在您的$.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 –