servlet+json+ajax整合

來源:互聯網
上載者:User

類比下拉式清單二級菜單聯動

       

1、頁面

       <tr>
<td align="right"><font color="red">*</font>一級服務類型:</td>
<td>
<select name="dept" id="dept" onchange="loadDeptChild(this.options[this.options.selectedIndex].value)"/>
<option value="0">請選擇...</option>
<c:forEach items="${depts}" var="dept">
<option value ="${dept.id }">${dept.name }</option>
</c:forEach>
</select>
<span style="color:red">${errDept}</span>
</td>
</tr>
<tr>
<td align="right">二級服務類型:</td>
<td>
<select name="deptChild" id="deptChild">
<option value="0">請選擇...</option>
</select>
</td>
</tr>

           

2、js

function loadDeptChild(dept){
var url="servlet/CustomerServlet?action=loadDeptChild&dept="+dept;
$.get(url, null, function(data){
var objs=eval("("+data+")"); //解析json對象
var deptChild=$("#deptChild");
deptChild.empty(); //初始化否則會追加
deptChild.append("<option value='0'>請選擇...</option>");
for(var i=0;i<objs.length;i++){
deptChild.append("<option value='"+objs[i].id+"'>"+objs[i].name+"</option>");
}
});
}

    

3、servlet

    /**
* 實現服務類型select二級聯動
*
* @throws ServletException
* @throws IOException
*/
public void loadDeptChild() throws ServletException, IOException {
// 設定頁面utf-8編碼
// response.setContentType("text/html;charset=utf-8");
// 可以自動識別為Json對象,否則eval解析json無效
response.setContentType("application/x-javascript;charset=UTF-8");
PrintWriter out = response.getWriter();


Integer dept = Integer.parseInt(request.getParameter("dept"));
List<Dictionary> models = customerDao.getDeptChilds(dept);
if (models != null && models.size() > 0) {
//構造json對象
StringBuffer json = new StringBuffer();
json.append("[");
for (Dictionary model : models) {
json.append('{');
json.append("id:").append(model.getId()).append(",");
json.append("name:").append("'").append(model.getName().trim()).append("'");
json.append("},");
}
json.deleteCharAt(json.length() - 1);
json.append("]");
out.println(json.toString());
out.close();
} else {
out.println("[{id:0,name:''}]");
out.close();
}
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.