一、javascript部分
<script type="text/javascript">
//ajax的使用
var xmlHttp;
function createXMLHttpRequest() {
//表示当前浏览器不是ie,如ns,firefox
if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function validate() {
alert("1");
createXMLHttpRequest();
var username = document.getElementById("username").value;
var url = "user_validate.action?username=" + username + "×tampt=" + new Date().getTime();
alert("2");
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange=callback;
xmlHttp.send(null);
}
function callback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var resTextSpan = document.getElementById("resText");
resTextSpan.innerHTML = "<font color='red'>" +
xmlHttp.responseText + "</font>";
}
}
}
</script>
二、struts.xml部分
<action name="user_validate" class="loginAction" method="check_loginName"/>
三、java部分
public String check_loginName(){
PrintWriter out = null;
try {
String responseText = "";
HttpServletResponse response = ServletActionContext.getResponse();
//设置字符集
response.setCharacterEncoding("UTF-8");
out = response.getWriter();
//读取请求参数
String loginName = ServletActionContext.getRequest().getParameter("username");
if(loginName == null || "".equals(loginName)){
responseText="用户不能为空";
}
out.println(responseText);
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
out.close();
}
return null;
}
<script type="text/javascript">
//ajax的使用
var xmlHttp;
function createXMLHttpRequest() {
//表示当前浏览器不是ie,如ns,firefox
if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function validate() {
alert("1");
createXMLHttpRequest();
var username = document.getElementById("username").value;
var url = "user_validate.action?username=" + username + "×tampt=" + new Date().getTime();
alert("2");
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange=callback;
xmlHttp.send(null);
}
function callback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var resTextSpan = document.getElementById("resText");
resTextSpan.innerHTML = "<font color='red'>" +
xmlHttp.responseText + "</font>";
}
}
}
</script>
二、struts.xml部分
<action name="user_validate" class="loginAction" method="check_loginName"/>
三、java部分
public String check_loginName(){
PrintWriter out = null;
try {
String responseText = "";
HttpServletResponse response = ServletActionContext.getResponse();
//设置字符集
response.setCharacterEncoding("UTF-8");
out = response.getWriter();
//读取请求参数
String loginName = ServletActionContext.getRequest().getParameter("username");
if(loginName == null || "".equals(loginName)){
responseText="用户不能为空";
}
out.println(responseText);
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
out.close();
}
return null;
}