对于新手,很多哥们都不懂怎么使用ajax异步校验,下面给一个简单完整的demo,希望对大家有帮助
先看一下效果图
首先jsp页面代码
1.js代码
$().ready(function(){
$("#user").blur(function(){
if($("#user").val()!=""){
$.ajax({
type :"get",
url : "users/user.action",
data : "user="+ $("#user").val(),
dataType : "json",
success : function(json) {
$.each(json, function(key, val){
if (key == "isTrue" && val == "true"){
$("#error").html("<font color='red'>该用户名已经存在!</font>");
return false;
}else{
$("#error").html("<font color='red'>该用户名可以使用!</font>");
}
})
},
error : function() {
alert("网络连接出错,请稍后重试");
}
})
}
})
});
</script>
2.body代码
<body>
用户名:<input type="text" value="" id="user">
<label id="error"></label>
<br><br>
密码:<input type="text" value="" id="passsword">
</body>
然后是struts.xml代码
<struts>
<package name="users" extends="struts-default" namespace="/users">
<action name="user" class="com.ajax.action.Ajax" method="codeName">
</action>
</package>
</struts>
最后是action代码
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.alibaba.fastjson.JSONObject;
public class Ajax {
private String user;
public void codeName() throws IOException {
String isTrue;
JSONObject jsonObject = new JSONObject();
HttpServletResponse response = ServletActionContext.getResponse();
if("admin".equals(user)){
isTrue="true";
}else{
isTrue="false";
}
jsonObject.put("isTrue", isTrue);
response.getWriter().print(jsonObject);
response.getWriter().flush();
response.getWriter().close();
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}