sending http request with ajax each time select bo

2019-03-04 04:40发布

问题:

Hi I am using jquery to get data from mysql. It works wonderfully but I need it to update a select box when another select box is changed. Here is what I have for jquery:

$("#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>");
                });

      } 
    });

  }); 

So what I am doing here is updating the select box #output each time #airports select is changed. It only works the first time it is changed and then does not do it again. But I do get the alert with the correct value when changed. Here are my select boxes:

<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>

Does anyone know why this is not working? Is there a solution? Thank you in advance for any help.

回答1:

I'm not sure why you are using live - is the original select sometimes replaced via AJAX as well? It may be, however, that you simply need to clear the original values first since you are only appending the new ones.

$("#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>");
         });
      } 
    });

});