Ajax 多级联动(Struts1.x与Strurts2.x)以市为例子上代码:(如有问题可以加QQ:2250680083)
1、导入包json-lib-2.2.3-jdk15.jar,引入jQuery如果联网建议使用Google的,地址为:<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
2、页面代码如下:var url="/" +lemis.WEB_APP_NAME + "/monitor/comEditShi.do";
//初始化市区
function inni_city(){
jQuery.ajax({
url : url,
data:{method: 'ajaxGetCity'},
type : "post",
async: false,
cache : false,
dataType : "json",
success:onchangecallback
});
function onchangecallback(data){
var str="<option value=''>请选择</option>" ;
for(var i=0;i<data.length;i++){
if(s8==(data[i].key)){
str+= "<option selected=true value='"+data[i].key+"'>"+data[i].value+ "</option>";//应对IE6的方法($("").val(值)会有问题)
}else{
str+= "<option value='"+data[i].key+"'>"+data[i].value+ "</option>";
}
}
$( "#所放位子ID").html(str);
}
}
3、配置action(自己配置)
4、Java代码
public class ComEditShi extends ActionLeafSupport {
/****获取市区
**/
public ActionForward ajaxGetCity(ActionMapping mapping, ActionForm actionForm,
HttpServletRequest request, HttpServletResponse response) throws AppException, IOException{
List<Param> zihanTypes =new ArrayList<Param>();
AjaxData msg1 = new AjaxData();//自己的方法
AjaxData.java
|
||
public class AjaxData { /** * 省厅监测,获取市 * @author 紫寒 * @return */ public LinkedHashMap getShi_st() { AjaxDataDAO rd = new AjaxDataDAO(); try { return rd.getShi_st();//自己方法
e.printStackTrace(); } return null; } } |
Set<Map.Entry<String, String>> entryseSet=mapaab061.entrySet();
for (Map.Entry<String, String> entry:entryseSet) {
Param param = new Param();
Param.java
|
public class Param { private Object entity; //预留 private String value; private String key; public Param() { } public Param(String value, String key) { this.value = value; this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getkey() { return key; } public void setkey(String key) { this.key = key; } public Object getEntity() { return entity; } public void setEntity(Object entity) { this.entity = entity; } } |
param.setValue(entry.getValue());
zihanTypes.add(param);
}
JSONArray jsonObj = JSONArray.fromObject(zihanTypes);
sendMsg(jsonObj.toString(),response); //Structs1.x
// sendMsg(jsonObj.toString()); //Structs2.x
Structs1.x | Structs2.x |
private void sendMsg(String string, HttpServletResponse response) { // TODO Auto-generated method stub response.setCharacterEncoding("UTF-8"); try { response.getWriter().write(string); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } |
private void sendMsg(String string) { HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("UTF-8"); response.getWriter().write(string); } |
}
}
5、相应的级联方法用jQuery的onchange事件就OK了!
6、祝技术分享愉快!