学习了servlet和ajax之后,做了一个简单的搜索框提示,用到了ajax、servlet、和json工具包
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
*{
margin: 0;
padding:0;
list-style: none;
}
</style>
</head>
<body>
<form >
<h1><input type="text" name="serachText" id="search"> <input type="submit" value="百度一下"></h1>
<ul id="ul">
</ul>
</form>
</body>
<script>
var search =document.getElementById("search");
var ul =document.getElementById("ul");
var xhr;
search.onfocus = function(){
ul.innerHTML="";
}
search.onkeyup = function(){
xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(data){
if(xhr.readyState==4 && xhr.status==200){
var result = xhr.responseText;
/*
*获取到的字符串为:"Served at: /webApp["java","javaweb","javascript","javeEE"]"
*需要对其进行处理后,在转化成json对象 ,采用字符串截取的方法
*/
var json = JSON.parse(result.substr(result.indexOf("["), result.length));
for(var i=0;i<json.length;i++){
var li = document.createElement("li");
var text =document.createTextNode(json[i]);
li.appendChild(text);
ul.appendChild(li);
}
console.log(json);
}
}
xhr.open("get", "search.action?search="+search.value, true);
xhr.send(); }
</script>
</html>
下面是servlet代码
package com.action;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
@WebServlet(name = "search", urlPatterns = { "/search.action" })
public class Search extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Map<String, String[]> map = new HashMap<String, String[]>();
static String[] strs1 = { "zbx", "zhang", "zhangh" };
static String[] strs2 = { "java", "javaweb", "javascript", "javeEE" };
static {
map.put("z", strs1);
map.put("j", strs2);
}
public Search() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
String str = request.getParameter("search");
String[] result = map.get(str);
System.out.println(JSONArray.fromObject(result).toString());
response.getWriter().write(JSONArray.fromObject(result).toString());
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}