【问题标题】:AJAX Receive multiple dataAJAX 接收多个数据
【发布时间】:2016-01-15 10:40:18
【问题描述】:

我正在尝试填充一些下拉字段。我有以下下拉列表:

  1. 大陆
  2. 国家
  3. 运动

我想选择第一个 Continent,然后选择 Country 和 Sport 以动态填充。示例:

  1. 欧洲 ->(所有欧洲国家都正确显示,它们在 db 中)。

  2. 我选择阿尔及利亚;运动名称应出现在下拉列表中。 json 是正确的,但我知道 ajax 是错误的! 这是我的代码:

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

    这是我得到的:

有什么建议吗?

【问题讨论】:

标签: javascript json ajax http-get


【解决方案1】:

为什么只有在大陆发生变化的情况下才重新加载体育列表?您是说您希望在国家/地区发生变化时更新运动列表,这不是您的代码正在做的事情。

试试这个(省略任何格式或文本元素):

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

此外,您代码中的val.id 与国家和体育项目相同吗?

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多