簡體   English   中英

填充在第一個選擇中選擇的選項的第二個選擇 deoending

[英]Populate 2nd select deoending of option choosen in 1st select

我正在嘗試使用 PHP+MySQL+Ajax 在選擇中動態加載選項,但我不知道該怎么做

目前我在 2 個表單中有 2 個選擇,我需要發送表單 2 次,因此頁面將加載 2 次。 我想使用 ajax 改進我的代碼,這樣我的頁面會加載得更快並且更容易使用。

  • 選擇 1 有一個國家列表
  • 選擇 2 有來自選擇 1 中選擇的國家/地區的城市列表

選擇城市后,該城市的具體信息將顯示在屏幕上。

表格 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>

表格 2

<!-- 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";
    }
}
?>

讓 Ajax 無需刷新或提交表單即可工作。 您需要為 ajax 調用創建單獨的端點。 你應該有3個文件:

  • index.php - 在這里一並顯示國家表格、城市表格和城市信息。 國家數據將默認加載,其他數據將鏈接到各自的 Ajax 調用。
  • fetchCities.php - 使用此端點根據選定的國家/地區值獲取城市的下拉值。
  • cityInfo.php - 使用此端點根據選定的城市值獲取城市信息。

注意:如果您在 Ajax 調用中包含第二個參數,您可以將 fetchCities.php 和 cityInfo.php 合並到一個文件中,例如: action: "fetchCity"

您可以執行以下操作:

索引.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>';
}
?>

城市信息.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 提到的,您應該真正使用參數化查詢。 我知道這似乎是一些額外的工作,但相信我,這值得你花時間。

(評論太長了。)

讓我說清楚。 在單個頁面上:

  1. 該頁面使用所有國家/地區的列表進行初始化。 (無論是在構建頁面時,還是通過 AJAX。)
  2. 用戶從所有國家的列表中選擇一個國家。
  3. 第二個數據庫查找查找該國家/地區的城市。
  4. 然后對這些城市做了一些事情。

那一定是兩次查找。

既然你提到了 AJAX,你想在不重新加載頁面的情況下完成所有這些嗎? 請注意<form>想要重新加載頁面。 是的,您可以使用 AJAX,但是如果您不提交和重新加載頁面,為什么要使用<form>呢?

世界上完整的城市名單超過300萬個。 你在用那個大小的桌子嗎? 或者一些子集,例如“有漢堡王的城市”?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM