的步骤如下:
<?php
$serverName = "your_server_name";
$connectionOptions = array(
"Database" => "your_database_name",
"Uid" => "your_username",
"PWD" => "your_password"
);
//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
//Check if the connection is successful
if($conn === false) {
die(print_r(sqlsrv_errors(), true));
}
//Query to retrieve data from the table
$query = "SELECT category_name FROM categories";
//Execute the query
$result = sqlsrv_query($conn, $query);
//Fetch the data and store it in an array
$data = array();
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
$data[] = $row['category_name'];
}
//Encode the data in JSON format
echo json_encode($data);
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
//Event listener for the change event of the first dropdown
$("#firstDropdown").change(function() {
//Clear the options of the second dropdown
$("#secondDropdown").html("");
//Get the selected value from the first dropdown
var selectedValue = $(this).val();
//Send an AJAX request to the PHP file to get the data for the second dropdown
$.ajax({
url: "getData.php",
type: "POST",
dataType: "json",
data: { selectedValue: selectedValue },
success: function(data) {
//Iterate over the data and append options to the second dropdown
$.each(data, function(index, value) {
$("#secondDropdown").append("<option>" + value + "</option>");
});
}
});
});
});
</script>
</head>
<body>
<select id="firstDropdown">
<!-- Options for the first dropdown -->
</select>
<select id="secondDropdown">
<!-- Options for the second dropdown will be dynamically populated -->
</select>
</body>
</html>
以上代码中,通过监听第一个下拉列表的change事件,当选择项发生变化时,发送一个AJAX请求到"getData.php"文件,并将选中的值作为参数传递给PHP文件。PHP文件根据传递的参数从SQL Server数据库中获取相应的数据,并将数据以JSON格式返回。在JavaScript中,通过遍历返回的数据,将每个值作为选项添加到第二个下拉列表中。
请注意,以上代码仅为示例,实际应用中需要根据具体情况进行修改和适配。另外,腾讯云提供了多种云计算相关产品,如云数据库SQL Server、云服务器等,可以根据具体需求选择合适的产品进行部署和使用。
领取专属 10元无门槛券
手把手带您无忧上云