function CheckForm(){ var pass; var msg; var url="${ctx}/crm/contact.action?method:checkForm"; var qq=document.getElementById("contact_QQ").value; var mobile=document.getElementById("contact_mobile").value; var email=document.getElementById("contact_email").value; $.ajax({ url : url, async:false, type : "post", dataType : "json", data : { QQ:qq, mobile:mobile, email:email }, success : function(data) { pass=data.pass; msg=data.msg; if(pass){ alert("儲存成功。"); }else{ alert(msg); } } }); if(pass) return true; else return false; } <button type="submit" class="btn btn-sm btn-primary savaBtn" name="method:save" onclick="return CheckForm()">儲存</button>
重要的一步就是 async:false, 因為ajax預設是非同步,即 預設為async:true 。設為false後就可以把ajax中返回到前台的pass值在函數CheckForm中使用。
在Action中,
public void checkForm(){ String mobile=(String)getParameter("mobile", String.class); String email=(String)getParameter("email", String.class); String QQ=(String)getParameter("QQ", String.class); boolean pass=true; List mobileList = contactManager.find("from Contact where mobile=?",mobile); List emailList = contactManager.find("from Contact where email=?",email); List qqList = contactManager.find("from Contact where QQ=?",QQ); //mobile不為空白且size不為0,即有重複 if((!(mobile ==null || mobile.equals("")))&& mobileList.size()!=0){ pass=false; msg+="手機號:"+mobile+ " 重複 "; } if((!(email ==null || email.equals(""))) && emailList.size()!=0){ pass=false; msg+="email:"+email+" 重複 "; } if((!(QQ ==null || QQ.equals(""))) && qqList.size()!=0){ pass=false; msg+="qq號:"+QQ+" 重複 "; } JSONObject resultObject = new JSONObject(); resultObject.put("pass", pass); if(!(msg ==null || msg.equals(""))){ resultObject.put("msg", msg.substring(4)); }else{ resultObject.put("msg", msg); } System.out.println("=========="); System.out.println("pass"+pass); System.out.println(resultObject.toString()); responseWrite(resultObject.toString()); }