jQuery的區域性重新整理——get、post和ajax方法寫法小結
阿新 • • 發佈:2019-02-10
在前臺頁面的編寫中,為了考慮到業務的科學性和使用者的體驗性,常常需要驗證使用者的輸入資料是否合理有效。一般來講,普通的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" onblur="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(); } }); }