Select2使用ajax和php基于第一(多)选择填充第二个字段

时间:2014-08-27 02:11:28

标签: javascript php jquery ajax jquery-select2

我怎样才能做到这一点? 我有第一个多选选项字段(父域),我需要根据第一个的值弹出第二个(子域)

<select id="parentfield" name="parentfield[]" multiple>
    <option value="1">first value</option>
    <option value="2">second value</option>
    <option value="3">third value</option>
</select>

此父域应将值发布到php脚本,脚本将数据返回到子域,如下所示

<select id="childfield" name="childfield[]">
    <optgroup label="Group 1">
        <option value="1">first value child</option>
        <option value="2">second value child</option>
    </optgroup>
    <optgroup label="Group 2">
        <option value="3">third value child</option>
        <option value="4">fourth value child</option>
    </optgroup>
</select>

所以我有这个PHP代码返回一个json,我想用它来构建值 (Obs。:自定义组件中的joomla ajax请求)

<?php
$materiaspost = implode(',',JRequest::getVar('disciplina'));
$materias = carregarcampos('SELECT * FROM #__marqueicerto_materias WHERE disciplina IN ('.$materiaspost.') AND assunto=0 ORDER BY materia ASC','list');
foreach ($materias as $materia) {
    $submaterias = carregarcampos('SELECT * FROM #__marqueicerto_materias WHERE assunto='.$materia['id_materia'].' ORDER BY materia ASC','list');
    foreach ($submaterias as $submateria) {
        // $vetor[$materia['materia']][$submateria['materia']] = array($submateria['id_materia']=>$submateria['materia']);
        $vetor[$materia['materia']][$submateria['id_materia']] = $submateria['materia'];
    }
}
?>

应该如何看待我的jquery来实现这个目标? 我是否必须修改我的PHP代码以生成不同的json响应?

1 个答案:

答案 0 :(得分:0)

<html>
<head>
<title>Multiple drop down list </title>
<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='yourcurrentfilename.php?cat=' + val ;
}
</script>
</head>
<body>
<?Php

$cat=$_GET['cat']; 

$quer2="SELECT category,cat_id FROM category order by category"; 

if(isset($cat)){
$quer1="SELECT DISTINCT subcategory FROM subcategory where cat_id=$cat order by subcategory"; 
}

echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>";
while($cat_name = mysql_fetch_array($quer2)) {
if($cat_name['cat_id']==$cat){
    echo "<option selected value=".$cat_name['cat_id'].">".$cat_name['category']."</option>"."<BR>";
}
else{
    echo  "<option value=".$cat_name['cat_id'].">".$cat_name['category']."</option>";
    }
}
echo "</select>";

echo "<select name='subcat'><option value=''>Select Two</option>";
while($subcat_name = mysql_fetch_array($quer1)) {
echo  "<option value=".$subcat_name['subcategory'].">".$subcat_name['subcategory']."</option>";
}
echo "</select>";
?>
</body>
</html>