纯AJAX+Servlet (回忆)

几年前在前一家公司做项目的时候,ajax经常会用到,常见的ajax框架,toolkit也是了如指掌,做了对日后这些东东就在也没有关注过,这不今儿恰巧有个项目其中用AJAX实现更加快捷才得以再续前缘用了一把,做了个小小的例子,算是温故知新。


JSP:
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page pageEncoding="UTF-8"%>

<html>
<head>
<title>
ajax<%=request.getContextPath()%>
</title>
</head>
<body bgcolor="#ffffff">
<h1>
name:<input id="view_name" type="text" maxlength="20" onBlur="testName(this.id)" /> <br />
<input type="button" value="check" onClick="testName('view_name')" />
<div ></div>
</h1>

<script language="javascript">
function testName(txt_ctr){
   
   if (window.ActiveXObject && !window.XMLHttpRequest) {
       window.XMLHttpRequest=function() {
       return new ActiveXObject((navigator.userAgent.toLowerCase().indexOf('msie 5') != -1) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP');
    };
   }//取得XMLHttpRequest对象

//path是取得系统路径
       var txt_ctr=document.getElementById(txt_ctr);
	   var url = "/alfi/AjaxServlet?parm=" + txt_ctr.value ;
       var req=new XMLHttpRequest();
       if (req) {
           req.onreadystatechange=function() {
            if (req.readyState==4 && req.status==200) {//判断状态,4是已发送,200已完成
			 alert("req.status: " + req.status);
			 alert("req.responseTex: " + req.responseText);
                  if(req.responseText==11){
                  txt_ctr.style.color='green';
                  }else if(req.responseText==1){
                 txt_ctr.style.color='red';
                        }else{
                      txt_ctr.style.color='red';
                      }
                  }
          }
                         req.open('POST', url, true);
                         req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						 alert(txt_ctr.value);
                         req.send(txt_ctr.value);//发送参数如果有参数req.send("username="+user_name);用request取得
       }
}
</script>
</body>
</html>


servlet:AjaxServlet.java


	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, RemoteException, IOException{
		doPost(req, res);
	}

	
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
				
		res.setContentType("text/xml; charset=UTF-8");
	    String ctrl_value = req.getParameter("parm");
	    PrintWriter out = res.getWriter();
		String downStr="";		
		System.out.println("&&&&&&&&&&&&&" + ctrl_value);
		out.print(11);
		
   }


web.xml

 <servlet>
   <servlet-name>AjaxServlet </servlet-name>
   <servlet-class>com.autobacs.servlet.AjaxServlet </servlet-class>
  </servlet>

   <servlet-mapping>
     <servlet-name>AjaxServlet </servlet-name>
     <url-pattern>/AjaxServlet</url-pattern>
  </servlet-mapping>


你可能感兴趣的:(Ajax,jsp,xml,servlet,Microsoft)