简体   繁体   中英

AJAX Receive multiple data

I am trying to populate some drop down fields. I have the following dropdown:

  1. Continent
  2. Country
  3. Sport

I want to select first Continent, after that the Country and Sport to populate dynamically. Example:

  1. Europe -> (All Europe countries appear correctly, they are in db).

  2. I choose Algeria; the Sport names should appear on drop down. The json is correct but the ajax, I know, is wrong! Here is my code:

     $(document).ready(function(){ $('#select_continents').on('change', function(){ //continent drop down ID $('#select_countries').empty();// country drop down ID $('#select_sport').empty();// sport drop down ID $.ajax({ method: 'GET', url: './json.php', data: { json_continent_country : 1, continent : $('#select_continents').val(), json_country_sport : 1, country : $('#select_countries').val() } }) .done(function(data){ $.each(JSON.parse(data), function(i, val) { $('#select_countries').append('<option value="'+val.id+'">'+val.country_name+'</option>'); $('#select_sport').append('<option value="'+val.id+'">'+val.sport_name+'</option>'); }) }) .fail(function(){ alert('error'); }) }) }) 

    This is what I get:

在此处输入图片说明

Any advice?

Why are you reloading the sports list only in case the continent is changed? You are saying that you wish to update the sports list when the country changes, that's not what your code is doing.

Try this instead (omitting any formatting or text elements):

<script type="text/javascript">
$('#continent').on('change', function() {
  var continent= $('#continent').val();

  // update sport list
  $.ajax('./json.php', {
    data: {
      "continent": continent
    }, success: function(data) {
      // clear and update sports SELECT
      $('#country').html('');
      for (var i in data) {
        $('#country').append($('<option>').val(data[i].val_id).text(data[i].country_name)
      }
    }
  });
});

$('#country').on('change', function() {
  var continent= $('#continent').val();
  var country= $('#country').val();

  // update sport list
  $.ajax('./json.php', {
    data: {
      "continent": continent, // most likely not relevant, country itself should suffice
      "country": country  
    }, success: function(data) {
      // clear and update sports SELECT
      $('#sport').html('');
      for (var i in data) {
        $('#sport').append($('<option>').val(data[i].val_id).text(data[i].sport_name)
      }
    }
  });
});
</script>
<body>
<select id="continent">
  <option value="Europe">Europe</option>
</select>

<select id="country">

</select>

<select id="sport">

</select>
</body>

besides, your val.id in your code is the same for country and sport?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM