1.Java代码如下:
package com.eduask;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Demo4 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, 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">
var getName1Id=document.getElementById("name1");
getName1Id.οnblur=function(){
var xhr=getXhr();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
var doc=xhr.responseXML;
var e1=doc.getElementsByTagName("msg")[0];
var msg=e1.firstChild.nodeValue;
//alert(msg);
var span=document.getElementById("span1");
span.innerHTML="<font color=red>"+msg+"</font>";
}
}
}
xhr.open("post","/ajax/Demo4");
//设置消息头,告诉浏览器携带请求体数据;
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
var span=document.getElementById("span1");
span.innerHTML="正在加载数据"
xhr.send("name1="+getName1Id.value);
}
function getXhr(){
var xhr;
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("microsoft,xmlhttp");
}
return xhr;
}
</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>