无需POST

时间:2018-09-26 12:33:04

标签: javascript php html

在HTML模式中,我有2个下拉菜单可供选择,一个用于团队,另一个用于玩家。

团队下拉选择数据是从数据库中提取的。每个球员都被分配到一个团队。

我要做的是,当我更改球队下拉菜单选择时,球员下拉菜单选择项根据所选球队而改变,这意味着它将仅包含所选球队的球员。

==>我想做到这一点而无需关闭模式,也无需刷新页面。

<select id="teams" name="teams">
 <?php
 $sql = $bdd->query('SELECT * FROM teams;');
 while($fetch = $sql->fetch(PDO::FETCH_ASSOC)){ ?>                      
   <option id="opt-<?php echo $fetch['id_team']; ?>"><?php echo $fetch['name']; ?></option>
 <?php } ?>
</select>

<select id="players" name="players">
 <?php
 $sql = $bdd->query('SELECT * FROM players where id_team=...;');
 while($fetch = $sql->fetch(PDO::FETCH_ASSOC)){ ?>                      
   <option id="opt-<?php echo $fetch['id_player']; ?>"><?php echo $fetch['name']; ?></option>
 <?php } ?>
</select>

这怎么办?

2 个答案:

答案 0 :(得分:1)

我希望这会有所帮助。您将需要使用Ajax和Jquery库。

main.php

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="teams" name="teams">            
 <?php
 $sql = $bdd->query('SELECT id_team, name FROM teams;');
 while($fetch = $sql->fetch(PDO::FETCH_ASSOC)){ ?>                      
   <option id="opt-<?php echo $fetch['id_team']; ?>"><?php echo $fetch['name']; ?></option>
 <?php } ?>
</select>

<select id="players" name="players"></select>

<script>
    $( "#teams" ).change(function() {
        var id = $(this).children(":selected").attr("id");
        var id_split = id.split("-");
        $.ajax({
            url: "getPlayers.php",
            type: "post",
            data: {id: id_split[1]},
            success: function (response) {
                document.getElementById("players").innerHTML = response;
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(textStatus, errorThrown);
            }
        });
    });
</script>

getPlayers.php

<?php
if(isset($_POST['id'])){
  $id = $_POST['id']; 
    //sql connection
  $sql = $bdd->query("SELECT id_player, name FROM players where id_team = $id");
  while($fetch = $sql->fetch(PDO::FETCH_ASSOC)){ ?>                      
    <option id="opt-<?php echo $fetch['id_player']; ?>"><?php echo $fetch['name']; ?></option>
 <?php }
}
?>

答案 1 :(得分:0)

您需要以这种方式使用jQuery:

$("#teams").on('change',function(){
    $.ajax({url: "your_url_here", success: function(result){
       $.each(result, function( index, value ) {
          $('#players').append('<option value="'your_value here'">'your_data_here'</option>')
       });
    }});
});