试图掌握级联下拉菜单的概念

时间:2015-01-14 23:25:59

标签: php jquery html

我试图理解如何使用jquery在php脚本中使用级联下拉列表的概念。我能够获得第一个下拉列表而不是第二个。

第一个下拉列表包含mysql数据库中客户的客户ID和名称。 第二个下拉列表包含与客户ID链接的客户工具,这些客户ID是工具表中的外键。

任何人都可以查看代码并告诉我可能会误入歧途吗?

这是index.php

<!DOCTYPE html>
<html>

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Chained Select Tutorial</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2 /jquery.min.js"></script>
</head>

<body>
<?php
include('dbconnect.php');
$con=mysqli_connect($host,$user,$password,$db);
// An array of options for the first select box.
$result = mysqli_query($con, "SELECT * FROM customers ORDER BY Customer Asc ");

// Displays the posted info 
if(isset($_POST['submit']))
{ echo '<pre>'; print_r($_POST); echo '</pre>'; }
?>
<form action="" method="post">
<select id="cust" name="cust"><!-- Make sure to give the select box a id, this will make it much easier to target with jquery. -->
<?php
// Build the options for the first select box
while($row = mysqli_fetch_array($result)){ echo '<option value="'.$row[Cust_ID].'">'.$row[Customer].'</option>'; }
?>
</select>
<select id="models" name="models"><!-- Make sure to give the select box a id, this will make it much easier to target with jquery. -->
</select>
<input type="submit" name="submit" value="Submit">
</form>

<script>
$('#cust').change(function(){ //Basically saying when the first select box changes values run the function below.
var cust = $(this).val(); // Grab the value of the selection to send to the select-request.php via ajax
$.post('select-request.php', {cust:cust}, function(data){ // Run a ajax request and send the var make as a post variable named "make" and return the info in the "data" var.
    $('#models').html(data); // Have jquery change the html within the second select box with the "data" we got back from the ajax request.
});
});
</script>

</body>

</html>

这是select-request.php

<?php
error_reporting(E_ALL); //Remove this line for production, it simply will allow php to display any errors


//We check to see if the "cust" post has come through before we do any processing.
if(isset($_POST['cust']))
{ 
$con=mysqli_connect($host,$user,$password,$db); 
$result1 = mysqli_query($con, "SELECT Inst_Name FROM instruments WHERE Cust_ID='$_POST[cust]'");
while($row = mysqli_fetch_array($result1)){ echo '<option value="'.$row[Inst_Name].'">'.$row[Inst_Name].'</option>';

 }
?>

有谁能告诉我我哪里误入歧途?

1 个答案:

答案 0 :(得分:0)

在不知道控制台上的输出的情况下,我猜测jQuery将第一行作为php脚本的输出。换句话说,它只接收第一个... select-request.php正在回显。试试这个:

while($row = mysqli_fetch_array($result1)){ 
  $returnable .= '<option value="'.$row[Inst_Name].'">'.$row[Inst_Name].'</option> ';
}
echo json_encode($returnable);