在PHP中使用Jquery和Ajax的从属选择框

时间:2018-02-12 03:45:16

标签: javascript php jquery ajax

我想要一个从属选择框我可以将数据从我的数据库加载到选择框中,但是,当我点击显示所有国家/地区时所有选择框都有数据时,省将返回默认数据。我需要做的是当我点击显示所有国家/地区时,选择框中的所有数据都将重置为其默认数据,依此类推。

AJAX脚本:

$(document).ready(function(){
//Show Province
$("#sort-country").change(function(){
    var country = $(this).val();
    $.ajax ({
        url:"fetch_province.php",
        method: "POST",
        data: {country:country},
        dataType: "text",
        success: function(data){
            $("#sort-province").html(data);
        }
    });
});

//Show Town
$("#sort-province").change(function(){
    var country = $("#sort-country").val();
    var province = $(this).val();
    $.ajax ({
        url:"fetch_town.php",
        method: "POST",
        data: {country:country, province:province},
        dataType: "text",
        success: function(data){
            $("#sort-town").html(data);
        }
    });
});

//Show Barangay
$("#sort-town").change(function(){
    var country = $("#sort-country").val();
    var province = $("#sort-province").val();
    var town = $(this).val();
    $.ajax ({
        url:"fetch_barangay.php",
        method: "POST",
        data: {country:country, province:province, town:town},
        dataType: "text",
        success: function(data){
            $("#sort-barangay").html(data);
        }
    });
});
});

取消省份:

<?php 
require "connect.php";

$output = "";

$sql = "SELECT * FROM tblLocation WHERE country='".$_POST['country']."' ORDER BY province";
$result = mysqli_query($conn, $sql);
$output = "<option value=''>Show All Province</option>";
while ($row = mysqli_fetch_array($result)) {
    $output .= "<option value='".$row['province']."'>".$row['province']."</option>";
}

echo $output;

?>

Fetch Town:

<?php 
require "connect.php";

$output = "";

$sql = "SELECT * FROM tblLocation WHERE country='".$_POST['country']."' AND province='".$_POST['province']."' ORDER BY town";
$result = mysqli_query($conn, $sql);


$output = "<option value=''>Show All Town</option>";
while ($row = mysqli_fetch_array($result)) {
    $output .= "<option value='".$row['town']."'>".$row['town']."</option>";
}

echo $output;

?>

取Barangay:

<?php 
require "connect.php";

$output = "";

$sql = "SELECT * FROM tblLocation WHERE country='".$_POST['country']."' AND province='".$_POST['province']."' AND town='".$_POST['town']."' ORDER BY barangay";
$result = mysqli_query($conn, $sql);

$output = "<option value=''>Show All Barangay</option>";
while ($row = mysqli_fetch_array($result)) {
    $output .= "<option value='".$row['barangay']."'>".$row['barangay']."</option>";
}

echo $output;

?>

0 个答案:

没有答案