一个下拉列表依赖于另一个


One dropdownlist depending on the other

我开发了一个php网页,其中包含两个下拉列表(选择标签),其中一个用于显示汽车类型,如丰田,日产,雪佛兰等。

Toyota
Nissan
Chevrolet

另一个应用于显示车型,如丰田凯美瑞,丰田卡罗拉,丰田Cressida,丰田Eco等,具体取决于从第一个下拉列表中选择的汽车类型。

我使用PHP作为开发语言,加上Sybase作为数据库,我使用ODBC连接到它。我使用Windows-1256作为字符编码,因为我显示的数据是阿拉伯语。

我尝试使用Ajax来实现,但我不知道如何,因为我使用Ajax之前只返回一个值,但在这种情况下,我需要以以下格式回复一些数据库记录:-

15 "Toyota Camry"
16 "Toyota Corrolla"
17 "Toyota Cressida"
18 "Toyota Eco"

加上数据是用阿拉伯语发送的,而不是上面列出的英语,所以列表可能如下:-

15 "تويوتا كامري"
16 "تويوتا كرولا"
17 "تويوتا كرسيدا"
18 "تويوتا إيكو"

我如何使用Ajax做到这一点,并确保阿拉伯语文本将显示良好?

我等待你的回答和帮助和提前感谢.....

我的代码写在下面,使事情更清楚,对别人有用,并得到正确的答案:

第一个文件

showCarData.php File (Saved as ANSI PHP File)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<script src="js/jquery-1.3.2.min.js" type="text/javascript" /></script>
<script type="text/javascript"> 
$(document).ready(function()
{ 
$('#selectCarType').change(function ()
{ 
$('#selectCarModel option').remove();
$.ajax(
{
url: "getCarModels.php", 
dataType: 'json', 
data: { CarType: $('#selectCarType').val() }, 
async: true,
success: function(result)
{   
//var x = eval(result);
$.each(result, function(key, value) { $('#selectCarModel').append('<option value="' + key + '">' + value + '</option>'); } );
}
});
$('#selectCarModel').show(); 
});
});
</script> 
</head>
<body>
<select id="selectCarType">     
<option value="0" selected="selected">select car type</option>
<?php
//Connecting To The Database and getting $conn Variable       
$conn = odbc_connect("database","username","password");
//Connection Check
if (!$conn)
{
echo "Database Connection Error: " . $conn;
}
$sqlCarTypes = "SELECT DISTINCT CarTypeID AS CarTypeCode, CarTypeDesc AS CarTypeName FROM tableCarTypes ORDER BY CarTypeDesc ASC";
$rsCarTypes = odbc_exec($conn,$sqlCarTypes);
if (!$rsCarTypes)
{
echo "<option class='CarType' value='n' >Not Available</option>";
}                                   
else
{                                   
while ( odbc_fetch_row($rsCarTypes) )
{
//Assigning The Database Result Set Rows To User-Defined Varaiables
$CarTypeCode = odbc_result($rsCarTypes,"CarTypeCode");
$CarTypeName = odbc_result($rsCarTypes,"CarTypeName");
//Creating the options
echo '<option class="CarType" style="color:#060;" value="'. $CarTypeCode . '"';
echo '>' . $CarTypeName . '</option>' . "'n";               
}                                   
}
odbc_close($conn);
?>
</select>
<select id="selectCarModel">        
<option value="0" selected="selected">select car model</option>
</select>
</body>
</html>

和其他文件是

getCarModels.php File (Saved as ANSI PHP File)
<?PHP
//determine the Characterset
header('Content-Type: text/html; charset=windows-1256');
//Recieve CarType variable
$CarType =  $_GET['CarType'];
// initialize an array that will hold the rows 
$result = array();
if ($CarType != Null)
{
//Connecting To The Database and getting $conn Variable       
$conn = odbc_connect("database","username","password");
//Connection Check
if (!$conn)
{
echo "Database Connection Error: " . $conn;
}
$sqlCarModels = "SELECT DISTINCT CarModelID AS CarModelCode, CarModelDesc AS CarModelName FROM tableCarTypes WHERE CarTypeID='$CarType' ORDER BY CarModelDesc ASC ";
$rsCarModels  = odbc_exec($conn,$sqlCarModels);
if ( $rsCarModels )
{
while ( odbc_fetch_row($rsCarModels) )
{
$CarModelCode = odbc_result($rsCarModels,"CarModelCode");
$CarModelName = odbc_result($rsCarModels,"CarModelName");
$CarModelName = utf8_encode($CarModelName);
$result [$CarModelCode] = $CarModelName;
}
}
else
{
echo "No Data";
}
odbc_close($conn);
}
//send the result in json encoding
echo json_encode($result);
?>

我希望这清楚我问的问题,任何人都可以帮助我找到错误或我错过的东西,以适当的格式获得输出,而不是像第二个下拉列表中显示的那样无法读取的奇怪符号和字符。

谢谢提前

在这种情况下我所做的是:

  1. 我在服务器上构建了第一个下拉列表,例如,PHP while在数据库中的汽车类别上。我把这个类别的id作为optionvalue。生成的HTML看起来应该像这样:

    & lt;选择id ="cars-categories"比;& lt;选项值="1"在Toyota& lt;选项值= " 2 "祝辞Nissan& lt;选项值="3"祝辞Chevrolet…& lt;/select>

  2. 然后在页面上,使用JavaScript,我监听onchange事件的选择,并在发生时发送类别id到服务器

  3. 服务器上的
  4. PHP代码选择类别id并生成SELECT your_cols FROM product_table WHERE cat_id = $_GET['id']。发送结果为JSON, json_encode

  5. 最后,用javascript解析返回的数据并填充模型下拉列表。

下面是客户端脚本的样子:

<script type="text/javascript">
$(document).ready(function() {
    $('#cars-categories').change(function () {
        $('#car-models option').remove();
        $.ajax({
            url: "get_data.php",
            dataType: 'json',
            data: { category: $('#cars-categories').val() },
            async: true,
            success: function(json){
                $.each(json, function(key, value){
                    $('#car-models').append('<option value="' + value.id + '">' + value.name + '</option>');
                });
            }
        });
        $('#car-models').show();
    });
});
</script>

编码不应该是一个问题。

EDIT:根据问题作者的要求,这里有一种简单的方法可以从DB查询中获取所有行,并将它们作为JSON编码字符串发送回页面。

<?php
// connect to DB
...
// initialize an array that will hold the rows
$rows = array();
// sanitize the category id. since it is an int, it is safest just to cast it to an integer
$cat_id = (int)$_GET['category'];
$result = mysql_query("SELECT id, name FROM `models` WHERE cat_id = $cat_id");
while($row = mysql_fetch_assoc()){
   $rows[] = $row;
}
// do a regular print out. It is not going to the screen but will be returned as JavaScript object
echo json_encode($rows);
// you have to exit the script (or at least should not print anything else)
exit;
?>