我想要一个列出产品类别的选择框。选择一个类别后,我想同时从数据库中选择该类别中的产品。我需要在此应用程序中使用 AJAX 吗?关于这样做的任何例子?这是我正在使用的代码:
这些函数构建每个选择字段的选项。
function buildCategoryOptions($catId = 0)
{
$sql = "SELECT cat_id, cat_parent_id, cat_name
FROM tbl_category
ORDER BY cat_id";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());
$categories = array();
while($row = dbFetchArray($result)) {
list($id, $parentId, $name) = $row;
if ($parentId == 0) {
// we create a new array for each top level categories
$categories[$id] = array('name' => $name, 'children' => array());
} else {
// the child categories are put int the parent category's array
$categories[$parentId]['children'][] = array('id' => $id, 'name' =>
$name);
}
}
// build combo box options
$list = '';
foreach ($categories as $key => $value) {
$name = $value['name'];
$children = $value['children'];
$list .= "<option value=\"$key\"";
if ($key == $catId) {
$list.= " selected";
}
$list .= ">$name</option>\r\n";
foreach ($children as $child) {
$list .= "<option value=\"{$child['id']}\"";
if ($child['id'] == $catId) {
$list.= " selected";
}
$list .= "> {$child['name']}</option>\r\n";
}
}
return $list;
}
/* 为单选选项构建产品选项列表 */
function buildProductOptions($catId = 0)
{
$sql = "SELECT pd_id, pd_name, cat_id
FROM tbl_product
WHERE cat_id = $catId
ORDER BY pd_name";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());
$numProduct = dbNumRows($result);
$products = array();
while($row = dbFetchArray($result)) {
list($id, $name) = $row;
// we create a new array for each top level categories
$products[$id] = array('name' => $name);
}
// build combo box options
$list = '';
foreach ($products as $key => $value) {
$name = $value['name'];
$list .= "<option value=\"$key\"";
$list .= ">$name</option>\r\n";
}
return $list;
}
这是选择字段的页面:
$catId = (isset($_GET['catId']) && $_GET['catId'] > 0) ? $_GET['catId'] : 0;
$categoryList = buildCategoryOptions($catId);
$productList = buildProductOptions($catId);
<!--- Category Select --->
<select name="cboCategory" id="cboCategory" class="box">
<option value="" selected>-- Choose Category --</option>
<?php
echo $categoryList;
?>
</select>
<!--- Products Select : category is changed the products need to be from selected cat -
-->
<select name="selectOptions" id="selectOptions" class="box" multiple="multiple" >
<option>--Pick the other options--</option>
<?php
echo $productList;
?>
</select>