根据使用php,mqsql和ajax选择的另一个下拉框,填充一个下拉框
问题描述:
我正在尝试根据另一个下拉框中的选择填充一个下拉框.这是我的php代码:
I am trying to populate a drop down box, based on a selection from another drop down box. Here is what I have for php code:
<form id="inventory" method="POST" action="">
<fieldset>
<label for="area" >Select Shelf Area</label>
<select id="area" name="area">
<option value=""></option>
<?php $area = $conn->query("
select substring_index(location, ' ', 1) as area
FROM location GROUP BY substring_index(location, ' ', 1)");
while ($row = $area->fetch_assoc()) {
echo '<option value="' . $row['area'] . '" >' . $row['area'] . '</option>';
}
>
</select><br/>
</fieldset>
</form>
运行查询时,一切都很好,但是我需要获取此结果并将其用于填充另一个下拉框(<'上一个下拉框的值'>)在这里:>
When I run my query, all is fine, but I need to take the results of this and use it to populate another drop down box ( the <'value from previous drop down '>) which is here:
echo "<label for='location' id='label'>Select location:</label>";
echo "<select id='location' name='location'>";
echo "<option value=''>--Select Location--</option>";
$query = "SELECT location_id, location FROM location
WHERE location LIKE '<value from previous drop down box>'
ORDER BY location";
$result = $conn->query($query);
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row['location'] . '" >' . $row['location'] . '</option>';
}
有什么想法吗?谢谢吉姆
Any thoughts? Thanks Jim
答
这是我使用 JavaScript 和 Ajax 解决问题的方法:
This is how I solved my issue using JavaScript and Ajax:
$("#area").change (function(){
$("#acctRecords tbody tr").remove();
$('#label').show();
$('#label2').show();
$('#location').show();
$('#section').show();
$.ajax({
type: "POST",
async: true,
url: "area.php",
dataType:"json",
data: ({area: $('#area').val()}),
success: function(data) {
$('select#location').empty();
$('select#location').append('<option value="0">Select Option</option>');
//Populate options of the second dropdown
for(var x = 0; x < data.id.length; x++) {
$('select#location').append('<option value="'+data.id[x]+'">'+data.location[x]+'</option>');
} //end of each function
} // end of success
}); // end of ajax call
}); // end of area change function
这发布到我的HTML中:
This posts to my HTML of:
echo"<label for='location' id='label'>Select location:</label>";
echo"<select id='location' name='location'>";
echo"</select><br />";
完美工作!