使用ajax中success后的返回值

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());
}

猜你喜欢

转载自blog.csdn.net/weixin_42595284/article/details/82902379
今日推荐