方法参考了以下链接:
http://blog.csdn.net/jjting/article/details/8653953
http://hayageek.com/jquery-ajax-json-parsejson-post-getjson/
http://stackoverflow.com/questions/4969754/jquery-append-to-select-with-an-array
背景:在打开页面时向一个id为empList的select中动态添加符合某些条件的、以userName为text、以userId为value的options。
需要用到的库:
1.commons-lang-2.4.jar
2.commons-beanutils-1.8.3.jar
3.commons-collections-3.2.1.jar
4.commons-logging-1.1.jar
5.ezmorph-1.0.6.jar
6.json-lib-2.4-jdk15.jar
java自带的库:
net.sf.json.JSONArray;
net.sf.json.JSONObject;
JSP部分:
<select id="empList" class="form-control span12">
</select>
<script>
getDeptEmp();
</script>
Ajax部分:
function getDeptEmp(){
var depId = $('#depIdSpan').text();
$.ajax({
type : "Get",
url : "getDepEmpList.html",
data : "depId=" + depId + "&allemp=" + 0,
success : function(response){
alert(response);
var json = $.parseJSON(response);
addOptions(json, "#empList");
},
error : function(e){
var alertText = 'Error: ' + e;
addAlert("alert-error", alertText, "#alertdiv");
}
});
}
function addOptions(json, selectId){
for(var i = 0; i < json.length; i++){
alert(json[i].userName + " " + json[i].userId);
$(selectId).append('<option value="' + json[i].userId + '">' + json[i].userName + '</option>');
}
}
Controller部分:
@RequestMapping(value = "/getDepEmpList", method = RequestMethod.GET)
public @ResponseBody
String getDepEmpList(
@RequestParam(value = "depId") String depId,
@RequestParam(value = "allemp") String allEmp){
try{
JSONArray jsonA = UserManager.getDeptEmpList(Integer.parseInt(depId), Integer.parseInt(allEmp));
return jsonA.toString();
}
catch (NumberFormatException e){
return null;
}
}
Hibernate部分:
public static JSONArray getDeptEmpList(int depId, int allEmp){
JSONArray array = new JSONArray();
createSession();
String hql;
if(allEmp == DeptElementCode.UNASSIGNED_EMP)
hql = "from User as user where user.depId=:depId and user.userType=:userType and user.groId=:groId";
else
hql = "from User as user where user.depId=:depId and user.userType=:userType";
Query query = session.createQuery(hql);
query.setInteger("depId", depId);
if(allEmp == DeptElementCode.UNASSIGNED_EMP)
query.setInteger("groId", 0);
query.setInteger("userType", UserType.EMPLOYEE);
List <User>list = query.list();
java.util.Iterator<User> iter = list.iterator();
UserNameId nameid = new UserNameId();
User user = null;
while (iter.hasNext()) {
user = iter.next();
System.out.println(user.getUserId() + " " + user.getUserName());
nameid.setUserId(user.getUserId());
nameid.setUserName(user.getUserName());
array.add(nameid);
}
session.getTransaction().commit();
session.close();
System.out.println("array: " + array.toString());
return array;
}