对于ajax应用来说,把和控件榜定的数据用json来承载,既可以避免频繁调用httprequest,也可以避免xml带来的性能解释。
假设我们要有一个级联菜单,显示用户组以及下面的用户,我们可以这样做
$group_user = Array();
$groups = $db->getAll("select * from $dbutils->group");
for ($i = 0, $count = count($groups); $i < $count; $i++) {
$users = $db->getAll("select * from $dbutils->user_group ug,$dbutils->user u where ug.user_id = u.user_id and ug.group_id = ".$groups[$i]['group_id']);
$group_user[$groups[$i]['group_id']]['users'] = $users;
}
$json = new JSON(JSON_LOOSE_TYPE);
$group_user_json_data = $json->encode($group_user); //将数据从php数组转换成javascript数组
$group_user_javascript_data = '<script type="text/javascript">' . "\n"
. '<!-- // associated javascript data' . "\n"
. 'var group_user_json_data = '
. $group_user_json_data . ";\n"
. '-->' . "\n"
. '</script>';
在模板表单里面
<?php
echo $group_user_javascript_data; //把json的数据显示出来
?>
<script language="javascript" type="text/javascript" >
function addOptions(optionList, optionMenu)
{
removeOptions(optionMenu); // clear out the options
for (var i=0; i < optionList.length; i++) {
optionMenu[i] = new Option(optionList[i].truename, optionList[i].user_id);
}
}
function removeOptions(optionMenu)
{
len = optionMenu.options.length;
for (var i=len-1; i >=0 ; i--) {
optionMenu.options[i] = null;
}
}
function change_group() {
var users = group_user_json_data[document.getElementById('receive_group').value]['users'];//从json里面得到对象
addOptions(users, document.getElementById('receive_user'))
}
</script>
<tr>
<td width="10%" >接收部门</td>
<td width="80%"><select name="receive_group" onchange="change_group()"><?php echo build_group_select(''); ?></select></td>
</tr>
<tr>
<td>接收人</td>
<td><select name="receive_user" id="receive_user"></select></td>
</tr>