一个下拉列表取决于另一个

时间:2022-05-17 14:19:14

I develop a php web page that contains two dropdownlists (select tags) as one of them used to display the car types like Toyota, Nissan, Chevrolet and so on.

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

Toyota
Nissan
Chevrolet

The other should be used to display the car models like Toyota Camry, Toyota Corrolla, Toyota Cressida, Toyota Eco and son on depeding on the Car Type selected from the first dropdownlist.

另一个应该用于显示汽车模型,如丰田凯美瑞,丰田Corrolla,丰田Cressida,丰田Eco和儿子依赖从第一个下拉列表中选择的汽车类型。

I use PHP as a development language plus Sybase as database and I connect to it using ODBC. I use Windows-1256 as Character Encoding as my displayed data is Arabic.

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

I try to use Ajax to implement that but I do not know how as I used Ajax before to return one value only but in this case I need to reply with some database records in the following format:-

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

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

plus that the data is sent in arabic not in English as listed above so the list may be as the following:-

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

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

how I can do that using Ajax and make sure that the Arabic text will be displayed well?

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

I wait your answer and help and Thanks in advance .....

我等你的回答和帮助,并提前致谢.....

My Code is written in the following to make things more clear and be useful for others and to get the right answer:

我的代码编写如下,以使事情更清晰,对其他人有用,并得到正确的答案:

The first file

第一个文件

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>

and the other file is

而另一个文件是

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);
?>

I hope this clear what I asked about and that any one could help me finding where is the error or the thing I miss to get the output in a proper format instead of the strange symbols and characters that could not be read as it shows in the second dropdown list.

我希望这清楚我所询问的内容,并且任何人都可以帮助我找到错误或我想念的东西,以正确的格式输出输出而不是奇怪的符号和字符无法读取,因为它显示在第二个下拉列表。

Thanks in advance

提前致谢

1 个解决方案

#1


1  

What I do in such scenario is the following:

我在这种情况下做的是以下内容:

  1. I construct the first dropdownlist on the server, with PHP while over the car categories from the database, for example. I place the id of the category as a value of the option. The resulting HTML should look something like this:

    我在服务器上构建了第一个下拉列表,例如,使用PHP,而不是来自数据库的汽车类别。我将类别的id作为选项的值。生成的HTML应如下所示:

    <select id="cars-categories"> <option value="1">Toyota</option> <option value="2">Nissan</option> <option value="3">Chevrolet</option> ... </select>

  2. Then on the page, with JavaScript, I listen for onchange event of the select and when occurs send the category id to the server

    然后在页面上,使用JavaScript,我会监听select的onchange事件,并在发生时将类别ID发送到服务器

  3. PHP code on the server picks the category id and makes a SELECT your_cols FROM product_table WHERE cat_id = $_GET['id']. Send the result as JSON with json_encode

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

  4. Finally, parse the returned data with JavaScritp and fill the model dropdownlist.

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

Here is what the client script basically can look like:

以下是客户端脚本基本上可以是这样的:

<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>

Encoding shouldn't be an issue.

编码应该不是问题。

EDIT: As requested by the author of the question, here is a simple way to get all the rows from the DB query and to send them back to the page as JSON encoded string.

编辑:根据问题的作者的要求,这是一个简单的方法来获取数据库查询中的所有行,并将它们作为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;
?>

#1


1  

What I do in such scenario is the following:

我在这种情况下做的是以下内容:

  1. I construct the first dropdownlist on the server, with PHP while over the car categories from the database, for example. I place the id of the category as a value of the option. The resulting HTML should look something like this:

    我在服务器上构建了第一个下拉列表,例如,使用PHP,而不是来自数据库的汽车类别。我将类别的id作为选项的值。生成的HTML应如下所示:

    <select id="cars-categories"> <option value="1">Toyota</option> <option value="2">Nissan</option> <option value="3">Chevrolet</option> ... </select>

  2. Then on the page, with JavaScript, I listen for onchange event of the select and when occurs send the category id to the server

    然后在页面上,使用JavaScript,我会监听select的onchange事件,并在发生时将类别ID发送到服务器

  3. PHP code on the server picks the category id and makes a SELECT your_cols FROM product_table WHERE cat_id = $_GET['id']. Send the result as JSON with json_encode

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

  4. Finally, parse the returned data with JavaScritp and fill the model dropdownlist.

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

Here is what the client script basically can look like:

以下是客户端脚本基本上可以是这样的:

<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>

Encoding shouldn't be an issue.

编码应该不是问题。

EDIT: As requested by the author of the question, here is a simple way to get all the rows from the DB query and to send them back to the page as JSON encoded string.

编辑:根据问题的作者的要求,这是一个简单的方法来获取数据库查询中的所有行,并将它们作为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;
?>