2012-11-01 34 views
0

嗨我正在使用jquery从MySQL获取数据。它工作很好,但我需要它来更新另一个选择框更改时选择框。这里是我的jQuery:发送http请求与Ajax每次选择框更改

$("#airports").live('change',function() 
    { 
     var selectVal = $('#airports :selected').val(); 
     alert(selectVal); 

    Send a http request with AJAX 

    $.ajax({          
     url: 'tras-hotels.php',       
     data: "n="+selectVal,              
     dataType: 'json',     
     success: function(data)   
     { 
     $.each(data, function(key,value){ 
        $('#output').append("<option value='"+value.id+"'>"+value.hotel+"</option>"); 
       }); 

     } 
    }); 

    }); 

所以我在做什么这里更新每个#airports选择时间#output选择框被改变。它只在第一次改变时才起作用,然后不再做。但是,当更改时,我确实得到了正确值的警报。这里是我的选择框:

<select name="airport" style="width: 220px;" id="airports"> 
      <option selected="selected">[Escoge Aeropuerto]</option> 
      <?php 
      while($tra = mysql_fetch_array($getAirports)){ 
       echo '<option value="'.$tra['taeropuerto_fklocacion'].'">'.$tra['taeropuerto_nombre'].'</option>'; 
       } 
      ?> 
      </select> 
      <label>Hotel</label> 
      <select name="hotel" id="output" style="width: 220px;"> 

      </select> 

有没有人知道为什么这是行不通的?有解决方案吗?预先感谢您的任何帮助。

回答

1

我不确定你为什么使用live - 原始选择是否有时也会通过AJAX替代?但是,您可能首先需要清除原始值,因为您只添加新值。

$("#airports").live('change',function() 
{ 
    var selectVal = $('#airports :selected').val(); 
    alert(selectVal); 

    var $output = $('#output').html(''); 

    $.ajax({          
     url: 'tras-hotels.php',       
     data: "n="+selectVal,              
     dataType: 'json',     
     success: function(data)   
     { 
     $.each(data, function(key,value) { 
       $output.append("<option value='"+value.id+"'>"+value.hotel+"</option>"); 
     }); 
     } 
    }); 

}); 
+0

非常感谢你这完美的工作! – liveandream