參考:how to dynamically change item of two related combobox
在短:
- 在
file1.php
,檢索的MySQL tbl1
和在組合框中甲顯示它。
- 在組合框甲的變化,取選項的值和通過AJAX它傳遞一個PHP文件
file2.php
並顯示輸出在由file2.php
產生file1.php
。
file2.php
,檢索mysql tbl2
與Id通過Ajax並生成組合框B。
實施例:
的index.php
<script type="text/javascript">
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function ajax_function(url, postData, id)
{
xmlhttp=GetXmlHttpObject();
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", postData.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send(postData);
}
function dispSecond(Id)
{
var params = 'Id=' + Id ;
var DivId = 'dispDiv';
ajax_function('ajax_display.php', params, DivId);
}
</script>
<?php
/* Mysqli query to retrieve and store in $ArrayList(Id=>Text)
Example: $ArrayList = array(1=>'Ford',2=>'Chevy');
*/
?>
<select id="drop_first" name="drop_first" onchange="return dispSecond(this.value);">
<option value="0">[Select]</option>
<?php
foreach ($ArrayList as $k=>$v)
{
echo '<option value="'.$k.'">'.$v.'</option>';
}
?>
</select>
<div id="dispDiv"></div>
ajax_display.php
<?php
$Id = isset($_REQUEST['Id']) ? $_REQUEST['Id'] : '';
if ($Id)
{
/* Mysqli query to retrieve and store in $SubArray where $Id
Example:
If $Id=1
$SubArray = array(1=>'Focus',2=>'Explorer');
If $Id=2
$SubArray = array(1=>'Cavalier',2=>'Impala', 3=>'Malibu');
*/
?>
<select id="drop_second" name="drop_second">
<option value="0">[Select]</option>
<?php
foreach ($SubArray as $k=>$v)
{
echo '<option value="'.$k.'">'.$v.'</option>';
}
?>
</select>
<?php
}
?>
注:
使用的mysqli或PDO來代替mysql的
下面演示和下載都是基於陣列,可以使用mysqli的檢索工具。
也可以嘗試使用$ .ajax,這也更容易。
DEMO | DOWNLOAD
我認爲你必須缺少代碼,因爲沒有提及你發佈的內容。 – Goose
你能不能發佈你的所有相關代碼 – webGautam
我還沒有做出下拉功能。但是,這是我的動態函數 –