下拉框的選項往往來自數據庫,典型做法是後台查詢出集合、序列化為 JSON 返回,前台遍歷後逐條 append 到 <select> 中。以下是一套完整可用的組合。
$.ajax({
url : "user!findUserList.action",
type : "post",
success: function(data){
var jsonObj = eval("("+data+")");
$.each(jsonObj, function (i, item) {
jQuery("#userList").append("<option value="+ item.userId+">"+ item.userRealName+"</option>");
});
},
error: function(text) {}
});
這裡用 value 承載用戶 id、顯示文本用真實姓名,正好符合「提交 ID、展示名稱」的常見需求。
public void findUserList() throws IOException {
List<UserModel> roleuserList = userService.findUserList();
String json = JSONArray.fromObject(roleuserList).toString();
writeHtml(json);
}
protected void writeHtml(String strData) {
try {
response.setContentType("text/html; charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.write(strData);
pw.flush();
pw.close();
} catch (IOException e) {
log.error("writeHtml()", e);
}
}
$("#userList").empty(),避免選項累積。