jsp文件以及js文件
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<base href="<%=basePath%>">
<title>添加用户</title>
<script type="text/javascript">
var xmlhttp;
function test(){
var username = document.getElementById("userName").value;
//创建ajax中的XMLHttpRequest对象,针对于不同浏览器
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("MSXML2.XMLHTTP.6.0")
}
xmlhttp.onreadystatechange= test1;
xmlhttp.open("GET","checkUserName.action?userName="+username, true);
xmlhttp.send(null);
}
function test1(){
var sp = document.getElementById("msg");
if(xmlhttp.readyState==4){
var flag = xmlhttp.responseText;
if(flag==0)
sp.innerHTML = "<font color='red'>用户名已存在</font>";
else if(flag==1)
sp.innerHTML = "<font color='green'>用户名可以使用</font>";
}
}
</script>
</head>
<body>
<s:form theme="xhtml" action="addUser.action" method="post">
<s:textfield id="userName" name="userName" label="用户名" οnblur="test()"></s:textfield>
<span id="msg"></span><<br/>
<s:submit value="提交"></s:submit>
</s:form>
</body>
</html>
XMLHttpRequest是Ajax最核心的对象,它有以下几个重要的方法或属性:
●open():建立到服务器的新请求。
●send():向服务器发送请求。
●abort():退出当前请求。
●readyState:提供当前 HTML 的就绪状态。
●responseText:服务器返回的请求响应文本。
其中readyState的五个状态含义为:
0: (Uninitialized) the send( ) method has not yet been invoked.
1: (Loading) the send( ) method has been invoked, request in progress.
2: (Loaded) the send( ) method has completed, entire response received.
3: (Interactive) the response is being parsed.
4: (Completed) the response has been parsed, is ready for harvesting.
0 - (未初始化)还没有调用send()方法
1 - (载入)已调用send()方法,正在发送请求
2 - (载入完成)send()方法执行完成,已经接收到全部响应内容
3 - (交互)正在解析响应内容
4 - (完成)响应内容解析完成,可以在客户端调用了
每一次readyState的变化都会触发readystatechange进而触发test1;
从上面代码可知当“姓名”的文本框失去焦点就会触发test()方法调用后台ACTION,action 返回的结果被responsetext接收,在script中做出最终要显示的提示
struts.xml文件
<action name="checkUserName" class="com.xzit.action.UserAction" method="checkUserName">
<result></result>
</action>
上面的<result></result>里面可以不写,如果报错,就写个已存在的页面,不会跳转的,action里execute的返回值必须为空!
xxx.action文件
//检查用户名是否已经存在
public String checkUserName(){
String flag = userService.checkUserName(userName);
HttpServletResponse response=ServletActionContext.getResponse();
PrintWriter out;
try {
out = response.getWriter();
if("success".equals(flag)){
System.out.println("1");
out.print("1");
out.flush();
out.close();
}else {
System.out.println("0");
out.print("0");
out.flush();
out.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null ;//一定不能够少
}