sending http request with ajax each time select box is changed

◇◆丶佛笑我妖孽 提交于 2019-12-02 16:21:21

问题


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

});


来源:https://stackoverflow.com/questions/13171361/sending-http-request-with-ajax-each-time-select-box-is-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!