1.从数据库读取部门的数据
<tr>
<td class="detail-left">部 门</td>
<td colspan="3">
<select name="deptID" id="deptID" style="width:100px;" οnchange="clickDept()">
<%
DeptModel[] depts = (DeptModel[])request.getAttribute("dept");
if(depts != null && depts.length > 0){
for(int i = 0; i < depts.length; i++){
%>
<option value="<%=depts[i].getDeptId() %>" ><%=depts[i].getDeptNme() %></option>
<%
}}%>
</select>
</td>
</tr>
jsp岗位的定义
<tr>
<td class="detail-left">岗 位</td>
<td colspan="3">
<select name="postId" id="postId" style="width:100px;">
<option value="POST_ID"></option>
</select>
</td>
</tr>
<script type="text/javascript">
var pid=$('postId').value;
new Request.JSON({
type:'json',
method: 'post',
async: false, //同步模式
url: 'userAction.do?action=AjaxDept&key='+$('deptID').value,
onSuccess: function(list){
//alert(list.length);
//var s=eval("("+list+")");
//alert(s);
//得到那个下拉框的对象
var tpost=document.getElementById('postId');
for(var i=0; i<list.length;i++){
// alert(list[i].postNme);
//对象点它的options方法[放它的下标]=创建一个Option对象
//简单的理解为 先创建一个Option对象 构造一个这样的对象 得 有2个值 显示的值还有一个是ID-----new Option(list[i].postNme, list[i].postId);
//我构造一个这样的对象有什么用呢? 因为 下拉框 也就是
//<select><option></option></select>这样的形式 我就得拿到 这个下拉框当前有多少个值了tpost.length
// 把那个Option对象赋予给它就好了tpost.options[tpost.length]
tpost.options[tpost.length] = new Option(list[i].postNme, list[i].postId);
}
// alert(list.list.length);
}
}).send();
}
</script>
action里面的方法
public ActionForward AjaxDept(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws DataBaseException, BusinessException {
response.setContentType("text/xml;charset=utf-8");
JSONObject json = new JSONObject();
int id=Integer.parseInt(request.getParameter("key"));
try{
//根据部门的id来查出这id下面的所有岗位
json.put("list", new JSONArray(postDao.getPostList(id)));
List<PostModel> s= this.postDao.getPostList(id);
System.out.println(s.size());
//这里 我没有采用第三方的JSON工具包 帮你添加了3个方法 来处理一个LIST变成一个JSON字符串的过程
response.getWriter().print(listToJson(postDao.getPostList(id)));
response.getWriter().close();
} catch (Exception e) {
e.printStackTrace();
json.put("message", e.getMessage());
response.getWriter().print(json);
response.getWriter().close();
} finally {
return null;
}
}
//解析成json
public static String listToJson(List<?> list) {
StringBuilder json = new StringBuilder();
json.append("[");
if (list != null && list.size() > 0) {
for (Object obj : list) {
json.append(objectToJson(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
} else {
json.append("]");
}
return json.toString();
}