我们这里使用HTML5的新特性datalist实现输入框的自动下拉提示,用datalist通过id与input关联起来,在搜索时就会出现下拉框。下面是HTML代码。
<!-- 输入框 --> <input type="text" size="50" id="search" name="search" list="browser" onkeyup="search()" οnblur="searchOnBlur()" /> <!-- 下面是内容展示区域 --> <datalist id="browser"> </datalist>
下面是js部分,使用的原生ajax,异步请求方式
onreadystatechange事件处理函数:该函数由服务器触发而不是用户,每次readyState属性的改变都会触发onreadystatechange事件
readyState表示Ajax的当前状态。用数值来表示是,0表示初始化、1表示正在加载、2表示已加载完、3表示服务器正在发送响应、4表示响应发送完毕
<script> //搜索框值改变的函数 function search() { var search = document.getElementById("search").value; var httpRequest = createXmlHttpRequest(); httpRequest.open("get","${pageContext.request.contextPath}/ui.do?cmd=search&search="+search,true); //httpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); httpRequest.send(); httpRequest.onreadystatechange = function () { if (httpRequest.readyState == 4 && httpRequest.status ==200){ clearContent(); var context = httpRequest.responseText; var json = eval("("+context+")"); var size = json.length; for (var i=0;i<size;i++){ var nextNode = json[i]; // 代表的是JSON格式数据的第i个元素 var option = document.createElement("option"); //给datalist添加option option.setAttribute("value",nextNode); //给option添加value document.getElementById("browser").appendChild(option) //把option添加到datalist上 } } } } function clearContent() { var browser = document.getElementById("browser"); for (var i=browser.childNodes.length-1;i>=0;i--){ browser.removeChild(browser.childNodes[i]); } } function searchOnBlur() {//失去焦点,清空。 clearContent(); } //支持XMLHttpRequest的浏览器 实际简单就一句话XMLHttpRequest xmlHttp = new XMLHttpRequest() function createXmlHttpRequest(){ var xmlHttp; try{ // Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); }catch (e){ // Internet Explorer try{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }catch (e){ alert("您的浏览器不支持AJAX!"); return false; } } } return xmlHttp; } </script>
servlet中,通过获得输入的参数向数据库查询出list,通过JSONArray.fromObject()解析成json能够解析的格式,使用JSONArray.fromObject()需要导入六个依赖包
@WebServlet(name = "UIServlet",urlPatterns = "/ui.do")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
var cmd = request.getParameter("cmd");
if ("search".equals(cmd)) search(request,response);
}
public void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { var name = request.getParameter("search");
//下面这一行是我的查询数据库的方法,根据你们情况而写。 var searchList = service.findLikeTopic(name);
List<String> list = new ArrayList<>(); for (int i=0;i<topicSearchList.size();i++){ list.add(topicSearchList.get(i).getTopic_title()); } response.getWriter().write(JSONArray.fromObject(list).toString()); }