index.jsp
<!--
<p>
<span class="tit">用户昵称:</span>
<input
type="text" name="nickname" class="input" onblur="checkname()"/>
<span id="userinfor" style="font-size:12px;color: gray;">长度小于15的英文字符或者数字</span>
</p>
-->
url: 'ajax/nametest',--我们对应的action
dataType: 'json',
data:"nickname="+nameobj.value,
success: function(data) {
var result=data.result;
if(result=="yes"){
$('#userinfor').text("恭喜你
该用户名可用");
$('#userinfor').css("color","green");
$('#userinfor').css("font-size","14px");
regname="yes";
}
else{
$('#userinfor').css("color","red");
$('#userinfor').css("font-size","14px");
regname="no" ;
}
},
error: function() {
$('#userinfor').text("出错了");
}
});
<action name="nametest" class="com.shida.action.NameTestAction">
<result type="json"></result>
</action>
//验证用户名是否已经存在
function checkname(){
$.ajax({
struts.xml
<package name="ajax" namespace="/ajax" extends="json-default">
</package>
NameTestAction.java
public class NameTestAction extends ActionSupport{
private String nickname;
UserBiz ub=new UserBiz();
private String result="";
public String execute(){
if(ub.getOneByName(nickname.trim())==null){
result="yes";
}
else{
result="no";
}
return SUCCESS;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
最后别忘了引入jquery.js文件啊 还一个
struts2-json-plugin-2.3.1.2.jar