1、首先绑定select和option标签 用name属性
<select id="schoolId" class="select-select2" style="width: 100%; text-align-last: center; height: 45px; border-radius: 3px; border-color: #dae0e8" name="schoolId">
<option value="0">-----请选择-----</option>
</select>
2、封装获取XMLHTTPRequest对象的方法
/*封装获取XMLHTTPRequest对象的方法 */
function getXMLHttpRequest(){
var http;
if(window.XMLHttpRequest){
http = new XMLHttpRequest();
}else{
http = new ActiveXObject("Microsoft.XMLHTTP");
}
return http;
}
3、通过js的AJAX加载所有的数据
function getSchool(){ var select =$("#schoolId"); //1、获取XMLHTTPRequest对象 var http = getXMLHttpRequest(); //2、建立请求 http.open("GET","<%=basePath%> school/SchoolGetAll", true); //3、发送请求 http.send(); //4、状态回调函数 http.onreadystatechange = function() { if (http.readyState == 4 && http.status == 200) { //将JSON字符串转化为JSON数组 var arr = JSON.parse(http.responseText); for ( var i in arr) { var op = "<option value='"+arr[i].schoolId+"'>" + arr[i].schoolName + "</option>" if (arr[i].schoolName != undefined) { select.append(op); } } } } }
其中basePath为自定义的根路径
<% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %>
4、最后在body中用onload属性起始加载数据填充
<body class="nav-md" onload="getSchool()">