输入"1",有提示,否则没有
suggest.jsp
#suggest { background-color: #e0e0e0; width: 200px; }
var xhr; function createXhr() { if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } } /* 提示词被选中 */ function select(divElm){ var inputElm = document.getElementById("keyword"); // 选中提示词 inputElm.value=divElm.innerText; // 关闭提示框 document.getElementById("suggest").innerHTML=""; } /* 输入后提示(输入1,有提示,否则没有) */ function search() { var inputElm = document.getElementById("keyword"); // 获取输入的内容 var inputWord = inputElm.value; createXhr(); xhr.onreadystatechange = function cbSearch() { if (xhr.readyState == 4 && xhr.status == 200) { var rsp = xhr.responseText; var json = eval("(" + rsp + ")"); // 获取提示词组 var array = json.array; var addHtml = ""; if (array!=null) { // 提示词组不为空,循环取词,添加div for ( var idx in array) { addHtml += "<div onclick=‘select(this)‘>" + array[idx] + "</div>"; } } //提示框 设 提示词 document.getElementById("suggest").innerHTML = addHtml; } }; xhr.open("get", "AjaxServlet?para=" + inputWord, true); xhr.send(null); }
<!-- 按键抬起才能取到输入内容,否则(keypress/keydown)是上次输入内容 --> <input type="text" id="keyword" onkeyup="search()"> <br> <div id="suggest"></div>
AjaxServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); AhJson aj = new AhJson(); String para=request.getParameter("para"); JSONObject jo = new JSONObject(); JSONArray a = new JSONArray(); if ("1".equals(para)){ a.add("1"); a.add("163"); a.add("12306"); jo.put("array", a); } response.getWriter().write(jo.toString()); }
时间: 2024-10-19 09:42:16