2011-11-25 51 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