下拉列表使用 jquery 和 sql 更新另一个下拉列表

Dropdown updates another dropdown with jquery and sql

如何用 jquery 更新另一个下拉菜单 sql。 表示来自数据库。

  $('#typeOfGlass').on('change', function(){
   console.log($('#typeOfGlass').val());
    $('#glassWidth').html('');
    if($('#typeOfGlass').val()==15){
        $('#glassWidth').append('<option value="19">19</option>');
        $('#glassWidth').append('<option value="20">20</option>');
        $('#glassWidth').append('<option value="21">21</option>');
    }else{
        $('#glassWidth').append('<option value="6">6</option>');
        $('#glassWidth').append('<option value="7">7</option>');
        $('#glassWidth').append('<option value="8">8</option>');
        $('#glassWidth').append('<option value="9">9</option>');
    }
});

我用这个,但我不知道如何从数据库中获取它。

$sqlq="SELECT DISTINCT daerah FROM kampung WHERE negeri='$negeri'";
    $result_set=mysqli_query($conn, $sqlq);
    while($row=mysqli_fetch_array($result_set, MYSQLI_ASSOC))
    {
        echo "<option value=".$row['daerah'].">".$row['daerah']."</option>";
    }

有什么想法吗?

您需要做的第一件事是更改查询或向您的 table 添加信息,这样程序就有办法确定是否将特定的 <option> 附加到<select>.

接下来,将所有行提取到一个数组中。这应该可以,但我没有测试它:

$rows = array();
while ($rows[] = mysqli_fetch_array($result_set, MYSQLI_ASSOC));

现在将此数据传递给 JavaScript:

echo "<script> var data = " . json_encode($rows) . "; </script>";

最后,当 #typeOfGlass 发生变化时,清除 #glassWidth,然后迭代 data 并仅附加相关元素,具体取决于 #typeOfGlass 的值。

实现这一目标的一个选项可能是使用 Ajax,正如@Rory McCrossan 所建议的那样。对于一个精确的答案来说,这个过程很安静,但我会给你一些你需要做的步骤。

如果您的查询在您的 php 中工作并且您的 html 也工作正常,您只需要将它们粘合在一起。所以你可以使用 javascript 来做到这一点。这是一个 Ajax 查询

的表达式
    $.ajax({
                url: www.yoursite.com, //file you made to process the request
                type: "GET", // or POST 
                success: function(data) { 
                    if (data.success === 'ok'){
                      // code of what to do if the call returns ok
                      // probably update your options
                    }
                },
                error: function(exeption){
                   var response = jQuery.parseJSON(exeption.responseText);
                   alert(response.error);
// what to do if the process fail
                }

因此使用 php 来处理查询并 return 您的新选项。如果您有更具体的零件库存,请告诉我们。祝你好运