【发布时间】:2015-05-01 08:02:01
【问题描述】:
我有两个从 MySQL 数据库生成的下拉列表。第二个下拉列表基于第一个下拉选择选项。
问题是,我无法生成第二个下拉数据。
我将第二个下拉值设为Undefined。但是第二个下拉列表中应该出现的值的数量是正确的。
请提出我在哪里做错了。谢谢。
以下是我的代码:
Index.php(连接)
<?php
//Create the connection
$con = mysqli_connect("localhost","root","root","echodeve_mfb_temp") or die("Some error occurred during connection " . mysqli_error($con));
// Write query
$strSQL = "SELECT bp_id, bp_name FROM mfb_billing";
// Execute the query.
$query = mysqli_query($con, $strSQL);
// Close the connection
//mysqli_close($con);
?>
Index.php(脚本)
<script>
$(document).ready(function() {
$("#item_1").change(function () {
var group_id = $(this).val();
$.ajax({
type: "POST",
url: "dropdown_select.php?item_1_id=" + group_id,
dataType: "json",
success: function(data){
//Clear options corresponding to earlier option of first dropdown
$('select#item_2').empty();
$('select#item_2').append('<option value="0">Select Option</option>');
//Populate options of the second dropdown
$.each( data, function(i, val){
$('select#item_2').append('<option value="' + val.hospital_id + '">' + val.hospital_name + '</option>');
});
$('select#item_2').focus();
},
beforeSend: function(){
$('select#item_2').empty();
$('select#item_2').append('<option value="0">Loading...</option>');
},
error: function(){
$('select#item_2').attr('disabled', true);
$('select#item_2').empty();
$('select#item_2').append('<option value="0">No Options</option>');
}
})
});
});
</script>
</head>
Index.php (HTML)
<body>
<label id="item_1_label" for="item_1" class="label">#1:</label>
<select id="item_1" name="item_1" />
<option value="">Select</option>
<?php
while($row = mysqli_fetch_array($query)) {
echo '<option value="'.$row['bp_id'].'">'.$row['bp_name'].'</option>'."\n";
}
?>
</select>
<label id="item_2_label" for="item_2" class="label">#2:</label>
<select id="item_2" name="item_2" />
</select>
</body>
dropdown_select.php(处理 PHP)
<?php
$item_1_id = $_GET['item_1_id'];
//Create the connection
$con = mysqli_connect("localhost","root","root","echodeve_mfb_temp") or die("Some error occurred during connection " . mysqli_error($con));
// Write query
$strSQL = "SELECT hospital_id, hospital_name FROM mfb_hospital WHERE bp_id = $item_1_id";
// Execute the query.
$query = mysqli_query($con, $strSQL);
$return_arr = array();
while($row = mysqli_fetch_array($query)) {
$row_array = array("name" => $row['hospital_name'],
"id" => $row['hospital_id']);
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
【问题讨论】:
-
你能告诉我 $query 字符串吗?
-
在 dropdown_select.php
$query = mysqli_query($con, $strSQL); -
$query = mysqli_query($con, $strSQL);打印_r($查询);检查一下,让我知道它给了什么?
-
此文件获取数据,然后使用它运行查询....如何打印该查询的结果....我的意思是我从另一个页面调用它?
-
在 print_r( $query ) 之后;添加模具;它将进一步停止执行脚本,并显示 $query。