struts + json + ajax +级联 例子
一,用到的jar包
json-lib-2.3-jdk15.jar
- jakarta commons-lang 2.5
- jakarta commons-beanutils 1.8.0
- jakarta commons-collections 3.2.1
- jakarta commons-logging 1.1.1
- ezmorph 1.0.6
二,需要的js文件
jquery-1.8.1.min.js
三,jsp代码
--js代码
<script type="text/javascript" src="/SSH2Test/js/jquery-1.8.1.min.js"></script>
function chanageFun(){
//得到下拉菜单的值
var sel = $("#sel1").val();
$.ajax({
type: "POST",
url: "<%=basePath%>op.action",
data: "sId="+sel,
dataType: "text",//如果没有次属性 火狐显示xmldocument
success: function(msg){
//var jsonObject = Json.evaluate(msg);
var jsonObject = eval('('+ msg +')');//转换成对象
//清空第二个下拉菜单
var sel2 = document.getElementById('sel2');
sel2.options.length = 0;
var opt = new Option("==请选择==", "");
sel2.add(opt);
//options 是java那的
for(var i = 0; i < jsonObject.options.length; i++){
var xText = jsonObject.options[i].text;
var xValue = jsonObject.options[i].value;
var optioni = new Option(xText, xValue);
sel2.add(optioni);
}
}
});
}
<td>
<select name="sel1" id="sel1" onchange="chanageFun()">
<option value="-1">请选择所在省份</option>
<option value="0">直辖市</option>
<option value="1">江苏省</option>
</select>
</td>
<td>
<select id="sel2" name="sel2"></select>
</td>
2.java 代码(后台)
private HttpServletRequest request = ServletActionContext.getRequest();
private HttpServletResponse response = ServletActionContext.getResponse();
public void cityList() throws IOException{
//防止中文乱码要放在第一行
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
JSONArray options = new JSONArray();
//获取ajax传的参数
String sid = request.getParameter("sId");
List<Object[]> cityList = esd.cityNum(sid);
for(int i = 0; i < cityList.size(); i++){
JSONObject option = new JSONObject();
option.put("text", cityList.get(i)[1].toString());
option.put("value", cityList.get(i)[0].toString());
options.add(option);
}
JSONObject result = new JSONObject();
result.put("options", options.toString());
response.getWriter().print(result.toString());
response.getWriter().flush();
}
//在数据库取数据
public List<Object[]> cityNum(String sId){
String sql = "select id, name from tbl_city where sid = "+ sId;
Session session = this.getHibernateTemplate().getSessionFactory().openSession();
Query query = session.createSQLQuery(sql);
return query.list();
}