jsp select 选中数据库传过来的值
<option value="${item.title}" ${item.up_id eq up_id ? "selected='selected'":""} >${item.title}option>
/ajax绑定下拉选项数据/
-----方式一(必须导入相应的json jar包文件和springMVC的配置文件)
1、java 后台代码
@RequestMapping("/findCateGoryAll1")
@ResponseBody
public Map<String, Object> findCateGoryAll1(Model model){
Map<String, Object> map=new HashMap<String, Object>();
List<CateGory> list=cateGoryService.findAll();
map.put("list", list);
return map;
}
2、 js文件
function addDishes(){
//清空原有select内的数据 foodCateGory 为select 的id
$("#foodCateGory").empty();
$.ajax({
data:"",
type:"POST",
dataType:'json',
async : false,//同步
url:"${pageContext.request.contextPath}/findCateGoryAll1",
success:function(data){
if(data.list==null){
alert("数据为空!!!");
}else{
$("#foodCateGory").append("");
for(var i = 0; i < data.list.length; i++) {
var id = data.list[i].id;
var name = data.list[i].name;
alert("id:"+id+",name:"+name);
//添加option元素
$("#foodCateGory").append("+name+"");
}
}
}
});
}
3、html文件
<select class="form-control" name="foodCateGory" id="foodCateGory">
</select>
-----方式二()
1、java 后台代码
/*ajax方式按照查询条件分页查询用户信息*/
@RequestMapping(value = { "/listAll" }, method = {RequestMethod.GET,RequestMethod.POST})
public void listAll(HttpServletResponse response) throws Exception {
List<UserInfo> userInfoList = userInfoService.queryAllUserInfo();
response.setContentType("text/json;charset=UTF-8");
PrintWriter out = response.getWriter();
JSONArray jsonArray = new JSONArray();
for(UserInfo userInfo:userInfoList) {
JSONObject jsonUserInfo = new JSONObject();
jsonUserInfo.accumulate("user_name", userInfo.getUser_name());
jsonUserInfo.accumulate("name", userInfo.getName());
jsonArray.put(jsonUserInfo);
}
out.println(jsonArray.toString());
out.flush();
out.close();
}
2、 js文件
//初始化评论用户下拉框值
$.ajax({
url: basePath + "UserInfo/listAll",
type: "get",
success: function(userInfos,response,status) {
$("#comment_userObj_user_name").empty();
var html="";
$(userInfos).each(function(i,userInfo){
html += " + userInfo.name + "";
});
$("#comment_userObj_user_name").html(html);
}
});
3、html文件
<div class="form-group">
<label for="comment_userObj_user_name" class="col-md-2 text-right">评论用户:</label>
<div class="col-md-8">
<select id="comment_userObj_user_name" name="comment.userObj.user_name" class="form-control">
</select>
</div>
</div>
总结:通过ajax 方式 动态绑定下拉选项值,不管是jsp 还是前后端分离的html思路是一样的。
ps:要导入 jquery 文件和bootstrap等必要文件。
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>