2016-01-15 40 views
1

我想填充一些下拉字段。我有以下的下拉菜单:AJAX接收多个数据

  1. 大陆
  2. 国家
  3. 体育

我想选择第一块大陆,在这之后的国家和体育动态填充。例如:

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

    这就是我得到:

enter image description here

有什么建议?

+0

试试这个例子:http://www.plus2net.com/php_tutorial/ajax_drop_down_list-demo.php – Chester

回答

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在你的代码是对国家和运动一样的吗?

+0

你是对的!谢谢! –

+0

好听,欢迎您! – SaschaM78