一周前,leader让我写一个类似百度的自动完成功能,呵呵,因为对ajax技术掌握的不好,所以苦恼了很久没有写出来
经过一周的学习,终于写出了一个ajax程序,以后的工作就好做多啦
index.jsp
<html>
<head>
<style >
#child{
color: #333;
width:200px;
height:200px;
border: 1px black;
}
ul,li{
margin-left:25px;
list-style: none;
line-height: 20px;
}
</style>
<script type="text/javascript">
var xmlHttp;
function autoSelect(word){
var keywd = word.value;
var url ="test.do?keywd="+escape(keywd);
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
xmlHttp.open("post",url);
xmlHttp.onreadystatechange = callback;
xmlHttp.send(null);s
}
function callback(){
if(xmlHttp.readyState ==4){
if(xmlHttp.status ==200){
var temp = xmlHttp.responseText;
var temparray = new Array();
if(temp != ''){
temparray = temp.split("?");
var str="<ul>";
for(i=1;i<temparray.length;i++){
str +="<li>"+temparray[i]+"</li>";
}
str +="</ul>";
document.getElementById("child").innerHTML =unescape(str);
}
}
}
}
</script>
</head>
<body>
<form action="test.do" method="post">
输入:<input name="keywd" id="keywd" οnkeyup="autoSelect(this);"/><br>
<div id="child"></div>
</form>
</body>
</html>
后台的servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String keywd = request.getParameter("keywd");
String ajaxStr ="a?b?c?d?m?abc";
response.setCharacterEncoding("utf-8");
PrintWriter pw = response.getWriter();
try{
pw.print(ajaxStr);
pw.close();
}catch(Exception e){
e.printStackTrace();
}
}
不管怎么说,值得庆祝的一天,呵呵呵,必定是程序员的一个好的开端,迈向一个优秀的软件工程师的路程又近了一步。
每天进步一点点,三个月后,一年后,两年后,呵呵,我的这个目标会实现的,一个优秀的软件工程师。