2011-11-25 44 views
2

使用VAR get函數之外考慮以下代碼片段:我需要在jQuery的

$('#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

這可能會幫助:http://stackoverflow.com/questions/6920445/place-ajax-get-into-a-javascript-variable –

回答

7

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

我不能,這$。只有當另一個字段有值時,get纔會執行,並且這個「if(amount> 0){}」將包含兩種情況的代碼。不管怎麼說,還是要謝謝你。 –

+0

@GustavoMartins我更新了我的答案,以提供更像您的代碼結構的解決方案。我需要看到你的實際代碼來進一步幫助。 – Jasper

+0

這個限制可以通過使用Jasper的建議來解決(你沒有說明需要滿足什麼其他條件,所以Jasper不能爲他們提供代碼),所以我很高興。聽起來像你只是需要另一個條件在你的變化函數,檢查量是否已經設置(由另一個領域?),或者如果它已經大於零。 –

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'); 
    } 
}) 
+0

這與問題代碼相同。 'if(amount> 0)'將在'amount = result;'之前被評估,'這意味着'amount'對於if語句總是等於'null'。 – Jasper

+0

不,因爲我得到async = false,所以代碼將被設置並等待直到ready函數完成,因此可以設置值並在函數之後使用。 – Niels

+0

只是讓人們知道這一點,這意味着瀏覽器將鎖定,直到AJAX調用完成(對於小的響應,這可能是從50ms到幾秒的任何地方)。 – Jasper