以邮箱验证功能为例
function ckEmail(){ var email = $('#txtEmail').val(); if(/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(email)){ $("#emailValidMsg").html("<img src='../images/load.gif' width='12' height='12' align='top'/><span style='color:#666666'>正在检测邮件可用性</span>"); var result = null;//定义全局变量,用来接收ajax返回参数 $.ajax({ url:"${ pageContext.request.contextPath }/user/ckEmailServer", type:"post", data:"user.email="+email, dataType:"json", async:false,//将同步标志改为false,代表执行完后续代码才返回结果 success:function(json){ if("ok" == json.message) { $("#emailValidMsg").html("<span style='color:#666666'><img src='../images/right.gif' width='12' height='12' align='top'/> 电子邮件地址可用</span>"); result = true; } else { $("#emailValidMsg").html("<img src='../images/wrong.gif' width='12' height='12' align='top'/> 抱歉,邮件地址已经被使用"); result = false; } } }); return result; } else if(email.length==0){ $("#emailValidMsg").html("<img src='../images/wrong.gif' width='12' height='12' align='top'/> 电子邮件不能为空"); return false; } else{ $("#emailValidMsg").html("<img src='../images/wrong.gif' width='12' height='12' align='top'/> 电子邮件地址格式错误"); return false; } }