1.Java代码如下:
packagecom.eduask;
importjava.io.IOException;
importjava.util.Date;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
publicclassDemo4extendsHttpServlet {
@Override
protectedvoidservice(HttpServletRequest req, HttpServletResponse resp)
throwsServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/xml;charset=utf-8");
String name=req.getParameter("name1");
if("tom".equals(name)) {
resp.getWriter().write("<root>abc"+"<msg>"+"用户名不可以注册"+"</msg>"+"</root>");
}else{
resp.getWriter().write("<root>abc"+"<msg>"+"用户名可以注册"+"</msg>"+"</root>");
}
}
}
2.xmldemo4.jsp代码如下:
<body>
请输入用户名: <input id="name1"type="text"name="name1">
<span id="span1"></span>
<script type="text/javascript">
vargetName1Id=document.getElementById("name1");
getName1Id.οnblur=function(){
varxhr=getXhr();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
vardoc=xhr.responseXML;
vare1=doc.getElementsByTagName("msg")[0];
varmsg=e1.firstChild.nodeValue;
//alert(msg);
varspan=document.getElementById("span1");
span.innerHTML="<font color=red>"+msg+"</font>";
}
}
}
xhr.open("post","/ajax/Demo4");
//设置消息头,告诉浏览器携带请求体数据;
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
varspan=document.getElementById("span1");
span.innerHTML="正在加载数据"
xhr.send("name1="+getName1Id.value);
}
functiongetXhr(){
varxhr;
if(window.XMLHttpRequest){
xhr=newXMLHttpRequest();
}else{
xhr=newActiveXObject("microsoft,xmlhttp");
}
returnxhr;
}
</script>
</body>
3.web.xml配置文件如下:
<!-- demo4 -->
<servlet>
<servlet-name>Demo4</servlet-name>
<servlet-class>com.eduask.Demo4</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Demo4</servlet-name>
<url-pattern>/Demo4</url-pattern>
</servlet-mapping>