在第一个选择中填充第二个选择选项

ehxuflar  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(331)

我试图使用php+mysql+ajax在select中动态加载选项,但我不知道怎么做
目前我有2个选择内2个表单,我需要发送表单2次,所以页面将加载2次。我想使用ajax改进我的代码,这样我的页面加载速度会更快,使用起来也会更方便。
选择1以获得国家/地区列表
选择2:从选择1中选择的国家/地区获得城市列表
选择城市后,该城市的特定信息将显示在屏幕中。

表格一

<?php include_once "conn.php"; ?>
<!-- Form 1 -->
<form action="" method="post">
    <select required id="Countries" name="Countries">
        <?php
        $sql = "SELECT distinct Country FROM cities order by 1 asc";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                echo '<option value="' . $row["Country"] . '">' . $row["Country"] . '</option>';
            }
        } else {
            echo "0 results";
        }
        ?>
    </select>
    <input type="submit" id="LoadCities" name="LoadCities" value="Load Cities" />
</form>

表格二

<!-- Store select 1 value in variable -->
<?php
if (isset($_POST['Countries'])) {
    $Countries = $_POST['Countries'];
}
?>

<!-- Form 1 -->
<form action="" method="post">
    <select required id="Cities" name="Cities">
        <?php
        $sql = 'SELECT  * FROM cities  where country="' . $Countries . '"';
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                echo '<option value="' . $row["City"] . '">' . $row["City"] . '</option>';
            }
        } else {
            echo "0 results";
        }
        ?>
    </select>
    <input type="submit" id="ShowInfo" name="ShowInfo" value="ShowInfo" />
</form>

在屏幕上显示城市信息:

<!-- Store select 2 value in variable and print selected options in screen-->
<?php
if (isset($_POST['Cities'])) {
    $City = $_POST['Cities'];
    $sql = 'SELECT * FROM cities where City="' . $City . '"';
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            echo '<p>Country: ' . $row["Country"] . '</p>';
            echo '<p>City: ' . $row["City"] . '</p>';
        }
    } else {
        echo "0 results";
    }
}
?>
kpbwa7wx

kpbwa7wx1#

让ajax在不刷新或提交表单的情况下工作。您需要为ajax调用创建单独的端点。您应该有3个文件:
index.php-在此处显示国家表格、城市表格和城市信息。默认情况下将加载国家数据,其他数据将链接到各自的ajax调用。
fetchcities.php-使用此端点根据所选国家/地区值获取城市的下拉列表值。
cityinfo.php-使用此端点根据选定的城市值获取城市信息。
注意:如果在ajax调用中包含第二个参数,则可以将fetchcities.php和cityinfo.php合并到一个文件中,例如:action:“fetchcity”
以下是您可以做的:
index.php

<?php include_once "conn.php"; ?>
<form action="" method="post">
    <select required id="Countries" name="Countries">
        <?php
        $sql = "SELECT distinct Country FROM cities order by 1 asc";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                echo '<option value="' . $row["Country"] . '">' . $row["Country"] . '</option>';
            }
        } else {
            echo "0 results";
        }
        ?>
    </select>
    <input type="submit" id="LoadCities" name="LoadCities" value="Load Cities" />
</form>

//empty city dropdown. You may remove the form element from it if not required.
<form action="" method="post">
    <select required id="Cities" name="Cities">
        <option disabled selected>Select a country first</option>
    </select>
</form>

//empty city info
<div id="cityInfo"></div>

<script>
    //whenever someone selects a country, hit the Ajax to fetch cities.
    $(document).on('change', '#Countries', function() {
        const selectedCountry = $(this).val();
        //run your cities Ajax here and pass selectedCountry value
        $.ajax({
                method: "POST",
                url: "fetchCities.php",
                data: {
                    Countries: selectedCountry
                }
            })
            .done(function(response) {
                //replace City dropdown with values returned from fetchCities.php file.
                $('#Cities').html(response);
            });
    });

    //whenever someone selects a city, hit the Ajax to fetch city information.
    $(document).on('change', '#Cities', function() {
        const selectedCity = $(this).val();
        //run your cities Ajax here and pass selectedCity value
        $.ajax({
                method: "POST",
                url: "cityInfo.php",
                data: {
                    Cities: selectedCity
                }
            })
            .done(function(response) {
                $('#cityInfo').html(response);
            });
    });
</script>

fetchcities.php

<?php include_once "conn.php";

if (isset($_POST['Countries'])) {
    $Countries = $_POST['Countries'];
    $sql = 'SELECT  * FROM cities  where country="' . $Countries . '"';
    $result = $conn->query($sql);

    $returnHtml = '';
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $returnHtml .= '<option value="' . $row["City"] . '">' . $row["City"] . '</option>';
        }
    } else {
        $returnHtml = '<option disabled selected>0 results</option>';
    }
    echo $returnHtml;
}else{
    echo '<option disabled selected>0 results</option>';
}
?>

cityinfo.php

<?php
include_once "conn.php";

if (isset($_POST['Cities'])) {
    $City = $_POST['Cities'];
    $sql = 'SELECT * FROM cities where City="' . $City . '"';
    $result = $conn->query($sql);

    $returnHtml = '';
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $returnHtml .= '<p>Country: ' . $row["Country"] . '</p>';
            $returnHtml .= '<p>City: ' . $row["City"] . '</p>';
        }
        echo $returnHtml;
    } else {
        echo "0 results";
    }
}else{
    echo "0 results";
}
?>

此外,正如dharman提到的,您应该真正使用参数化查询。我知道这似乎是额外的工作,但相信我,这是值得你花时间的。

gwbalxhn

gwbalxhn2#

(评论太长了。)
让我说清楚。在单个页面上:
该页面使用所有国家/地区的列表进行初始化(在构建页面时,或者通过ajax。)
用户从所有国家的列表中选择一个国家。
第二次数据库查找将查找该国的城市。
然后对这些城市采取了一些措施。
那一定是两次查找。
既然你提到了ajax,你想在不重新加载页面的情况下完成这一切吗?注意 <form> 要重新加载页面。是的,你可以变态地使用ajax,但是为什么要这么做呢 <form> 如果您不提交并重新加载页面?
全世界城市总数超过300万。你在用那张大table吗?或者一些子集,比如“有汉堡王的城市”?

相关问题