struts2下的Ajax

index.jsp

	<script type="text/javascript" src="js/xhr.js"></script>
	<script type="text/javascript">
		function check_userName(){
			
			//1 获取Ajax请求对象	
			var xhr = getXhr();
			//alert(xhr)
			//2 创建请求
			//alert(userName);
			xhr.open("POST","loginAction",true);
			xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
			//4 回调函数
			xhr.onreadystatechange = 
				function callBack(){
					if(xhr.readyState == 4 && xhr.status == 200){
						var text = xhr.responseText;
						//alert(text);
						//将接受到的json字符串转换成json对象
						var data = eval("("+text+")");
						//取出json对象里面的userNameSpan属性值赋值给id的userNameSpan的span标签
						document.getElementById("userNameSpan").innerHTML = data.userNameSpan;
					}
				}
			//模拟网络延迟效果			
			document.getElementById("userNameSpan").innerHTML = "正在验证ing...";
			//5 发送请求
			var userName = document.getElementById("userName").value;
			xhr.send("userName=" + userName);
		}
		//回调函数
		
		
	</script>
	
  </head>
  
  <body>
    userName:
    	<input id="userName" type="text" name="userName" onblur="check_userName()"/>
    	<span id="userNameSpan" style="color:red"></span>
   		<br/>
	passWord:
		<input id="passWord" type="password" name="passWord"/>
		<br/>
  </body>

  xhr.js

function getXhr(){
	var xhr = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject();
	return xhr;
}

  LoginAction.java

public String register(){
		
		//模拟网络延迟
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		if("yangkang".equals(userName)){
			userNameSpan = "该用户名已经被注册";
		}else{
			userNameSpan = "√";
		}
		
		return SUCCESS;
	}

	
	private String userName;
	private String passWord;
	private String userNameSpan;
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassWord() {
		return passWord;
	}
	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}
	public String getUserNameSpan() {
		return userNameSpan;
	}
	public void setUserNameSpan(String userNameSpan) {
		this.userNameSpan = userNameSpan;
	}

  

<struts>
	<package name="json" extends="json-default" namespace="/">
		<action name="loginAction" class="com.yangkang.action.LoginAction" method="register">
			<result type="json"></result>
		</action>
	</package>	
</struts>

  jar包:

ezmorph-1.0.3.jar
json-lib-2.1-jdk15.jar
struts2-json-plugin-2.2.3.1.jar
commons-logging-1.1.1.jar
freemarker-2.3.16.jar
ognl-3.0.1.jar
xwork-core-2.2.3.1.jar
struts2-core-2.2.3.1.jar
commons-beanutils-1.7.0.jar
commons-lang-2.5.jar
commons-fileupload-1.2.2.jar
javassist-3.11.0.GA.jar
commons-io-2.0.1.jar

 

 

 

源码地址:http://pan.baidu.com/s/1c0EqLEg

posted @ 2015-06-16 00:46  活下去  阅读(195)  评论(0编辑  收藏  举报