在前台页面的编写中,为了考虑到业务的科学性和用户的体验性,常常需要验证用户的输入数据是否合理有效。一般来讲,普通的js即可以做到,但更多时候往往需要跟后台进行交互。例如用户注册,判断用户所输入的用户名是否已经存在。下面用jQuery的get、post和ajax方法来实现判断,同时对这三种常见的局部刷新技术做一个小结:
注册页面:
<tr bgcolor="#FFFFFF">
<td height="25" width="15%" class="td_title">登录帐号<font color="red">*</font></td>
<td height="25" width="35%" colspan="3"><input id="loginId" name="userVO.loginId" size="30" οnblur="checkLoginId()" /><font color="red" id="loginId_message"></font>
</td>
</tr>
其中,onblur所触发的方法即是判断用户输入是否合理的方法。
判断用户输入是否已经存在的后台action:
<action name="PortalUser" class="com.xxx.action.UserAction" method="do{1}">
<result name="plainMessage">
<!-- 写在plainMessage对应的页面中(不是注册页面)
<s:actionmessage theme="plain" /> ->
</result>
</action>
public String validLoginId() throws UnsupportedEncodingException{
UserService userService = xxx.getUserService
boolean flag;
try {
flag = portalUserService.checkPortalUserLoginIdExist(portalUserVO);
if(flag == true)
{
this.addActionMessage("true");//给结果页面
}
else
{
this.addActionMessage("false");
}
} catch (Exception e) {
e.printStackTrace();
//action必须返回一个String,但是此action返回的string并不是给结果页面
return "plainMessage";
}
var LOGINID_VALID = false; jQuery("#loginId").val(jQuery.trim(jQuery("#loginId").val())); var loginId = jQuery("#loginId").val();
1.jQuery.get/post方式
function checkLoginId(){ if(loginId == ""){ jQuery("#loginId_message").html("请输入登陆账号"); return; } //前台处理action的URL var url = "<%=request.getContextPath()%>/User!validLoginId.action"; //get方式还可以这样写: //var url = "<%=request.getContextPath()%>/User!validLoginId.action?userVO.loginId" + loginId; jQuery.post(或get)( url, {"userVO.loginId":loginId}, //当get方式把请求参数跟在url后面时,这里可以直接写成{} //action成功处理后的回调response数据 function(response){ if(jQuery.trim(response) == "false"){ LOGINID_VALID = true; jQuery("#loginId_message").html(""); } else if(jQuery.trim(response) == "true"){ LOGINID_VALID = false; jQuery("#loginId_message").html("该登陆账号已存在,请重新输入"); jQuery("#loginId").focus(); } }); }
2.jQuery.ajax方式
这种方式直接把请求参数放到url后面,提交给后台action
function checkLoginId(){ if(loginId == ""){ jQuery("#loginId_message").html("请输入登陆账号"); return; } //前台处理action的URL var url = "<%=request.getContextPath()%>/User!validLoginId.action"; jQuery.post( url:url, type:get/post data:{"userVO.loginId":loginId}, //多个请求参数用,分隔 dataType:json,(text等) //action成功处理后的回调response数据 success:function(response){ if(jQuery.trim(response) == "false"){ LOGINID_VALID = true; jQuery("#loginId_message").html(""); } else if(jQuery.trim(response) == "true"){ LOGINID_VALID = false; jQuery("#loginId_message").html("该登陆账号已存在,请重新输入"); jQuery("#loginId").focus(); } }); }