SpringMVC中AJAX通过JSONArray向下拉列表中动态添加选项

来源:互联网 发布:cocos2d游戏源码 编辑:程序博客网 时间:2024/05/22 10:23
方法参考了以下链接:
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
http://www.sebarmeli.com/blog/2010/12/06/best-way-to-loop-through-an-array-in-javascript/

背景:在打开页面时向一个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 @ResponseBodyString 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";elsehql = "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;}

0 0
原创粉丝点击