1

我想要一个列出产品类别的选择框。选择一个类别后,我想同时从数据库中选择该类别中的产品。我需要在此应用程序中使用 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 .= ">&nbsp;&nbsp;{$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>
4

1 回答 1

3

是的,您确实需要在这里使用 ajax。检查以下代码和注释。

编写返回 a 的函数,该函数ActiveXObject()将执行 ajax 调用为

function getXMLHTTP() {
    var xmlhttp = false;
    try {
        xmlhttp = new XMLHttpRequest();
    } catch (e) {
        try {
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                try {
                    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e1) {
                    xmlhttp = false;
                }
            }
        }
    }

    return xmlhttp;
}

然后编写一个特定于您的站点的函数,该函数将获得所需的数据

function getProducts(){
var select1 = document.getElementById("cboCategory");
var strURL = "getproducts.php?city="+select1.options[select1.selectedIndex].value;

var req = getXMLHTTP(); // function to get xmlhttp object
if (req) {
    req.onreadystatechange = function() {
        if (req.readyState == 4) { // data is retrieved from server
            if (req.status == 200) { // which reprents ok status
                document.getElementById('productsdiv').innerHTML = req.responseText; // div to be updated
            } else {
                alert("[GET Products]There was a problem while using XMLHTTP:\n" + req.statusText);
            }
        }
    };
    req.open("GET", strURL, true); // open url using get method
    req.send(null);
}

}

此函数将在cboCategory选择选项的更改事件时调用,因此相应的 html 将是

<select onchange="getProducts()" id="cboCategory" class="box">
  ...
</select>
<!-- Can be anywhere on same page -->
<div id="productdiv"> </div>

您的 getproduct.php 页面将返回一个 html 作为字符串,该字符串将覆盖producstdiv您的 html 页面中标记的内容。

您还可以将 php 中的数据作为。检查它的标签 wiki 以获取更多信息。您也可以使用进行 ajax 调用。

于 2012-09-18T18:18:55.677 回答