我的第一个ajax 自动完成

一周前,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();
  }
 }

 

 

不管怎么说,值得庆祝的一天,呵呵呵,必定是程序员的一个好的开端,迈向一个优秀的软件工程师的路程又近了一步。

每天进步一点点,三个月后,一年后,两年后,呵呵,我的这个目标会实现的,一个优秀的软件工程师。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值