2016-01-15 43 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