springmvc ajax list,SpringMVC ajax异步回传list对象

1. commUtil 类

public static String convert2Json(List tempList, String idMethod, String valMethod){

if(tempList == null || tempList.isEmpty() || StringUtil.isNullOrEmpty(idMethod) ||                     StringUtil.isNullOrEmpty(valMethod)){

return "";

}

String arr = "[";

for (T obj : tempList){

Method method;

try {

arr += "{\"id\":\"";

method = obj.getClass().getMethod(idMethod);

arr += Long.parseLong(method.invoke(obj).toString()) + "\",";

arr += "\"name\":\"";

method = obj.getClass().getMethod(valMethod);

arr +=  method.invoke(obj).toString() + "\"},";

} catch (Exception e) {

e.printStackTrace();

}

}

int len = arr.length();

if (len > 1){

arr.substring(len - 1);

}

arr += "]";

return arr;

}

2. controller 类

@RequestMapping(params = "method=findUseEmsClampTypes")

@ResponseBody

public String findUseEmsClampTypes(HttpServletRequest request, HttpServletResponse response){

Long assemblyTypeId = RequestUtil.parseLong(request, "assemblyTypeId");

List useList = emsClampUseTypeManager.findUseEmsClampTypes(assemblyTypeId);

return CommUtil.convert2Json(useList, "getUseTypeId", "getUseType");

}

3. js

$.ajax({

type : "POST",

url : "${ctx}/ems/emsClampUtil.html?method=findUseEmsClampTypes",

data : "assemblyTypeId=" + assemblyTypeId,

success : function(data) {

var obj = eval(data);

$.each(obj,function(i){

if (obj[i].id == selectedUseTypeId){

$("#useTypeId").append("" + obj[i].name + "");

} else {

$("#useTypeId").append("" + obj[i].name + "");

}

$("#useTypeId").render();

});

}

});