通过onchange从php过滤datalist

时间:2016-08-26 11:24:10

标签: javascript php jquery html mysql

我是javascript的初学者
我从mysql中的表中选择包含类列表和输入的组件包含数据列表name

这里是我的简单代码:

<select class="form-control" name="class" id="class" onchange="" value="--">
    <option>--</option>
    <option>X NET 1</option>
    <option>X NET 2</option>
    <option>XI NET 1</option>
    <option>XI NET 2</option>
</select>
<input type="text" class="form-control" name="name" id="name" list="checkName" autocomplete="off" required>
<datalist id="checkName">
    <?php
        $sql_siswa = "SELECT name,class from student order by name;";
        $result = $conn->query($sql_siswa);
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()){
                echo "<option value=\"".$row["name"]."\">";
            }
        }
    ?>
</datalist>

所以,我想如果我选择类,datalist将通过php从过滤器中按类检索名称。 这里过滤如下:

$sql_siswa = "SELECT name from student where class like '".$_POST["class"]."' order by name;";
$result = $conn->query($sql_siswa);
if ($result->num_rows > 0){
    while($row = $result->fetch_assoc()){
        echo "<option value=\"".$row["name"]."\">";
    }
}

如何在onchange中实施此过滤器? 对不起,我没有尝试任何事情,因为我不知道该怎么办。

1 个答案:

答案 0 :(得分:1)

你应该尝试ajax来做到这一点

<select class="form-control" name="class" id="class" onchange="ajax_change(this.value)" >
<option value="">--</option>
<option value="X NET 1">X NET 1</option>
<option value="X NET 2">X NET 2</option>
<option value="XI NET 1">XI NET 1</option>
<option value="XI NET 2">XI NET 2</option>
</select>

在你的剧本中

function ajax_change(str){
 $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: {class: str},
        success: function (data) {            
           $("#checkName").html(data);
        },
        error: function (xhr) {
           //Do Something to handle error
           alert("some error found");
        }
    });
 }

在你的ajax.php

//include connection
if(isset($_POST["class"])){
$sql_siswa = "SELECT name from student where class like '".$_POST["class"]."' order by name;";
$result = $conn->query($sql_siswa);
if ($result->num_rows > 0){
    while($row = $result->fetch_assoc()){
        echo "<option value=\"".$row["name"]."\">";
    }
 }
}