异步的ajax实际上使用了单独的进程,因此无法获取到这个返回值,而且,在调用ajax()方法时你根本无法知道它什么时候会执行完毕。 因此对于异步的ajax来说,你无法主动的获取其返回值,只能提供回调方法,ajax对象可以将参数传递到你提供的回调方法中,如上面,自己通过回调函数获得了返回值。
//ajax验证name
var ajaxResult = false;//全局变量
function ajaxResultdeal(response){
ajaxResult = response; //传递给全局变量
if(ajaxResult == '1'){
ele.name.className="";//移除class
ele.imgs[0].setAttribute("src","img/right.jpg"); //对应图标
ele.imgs[0].style.display = "inline"; //显示
ajaxResult= true;
}
else{
ele.name.className="borderRed";//移除class
ele.imgs[0].setAttribute("src","img/wrong.jpg"); //对应图标
ele.imgs[0].style.display = "inline"; //显示
biaoqian1.innerHTML='该用户名已经存在';
ajaxResult=false;
}
ajaxResultreturn();
}
function ajaxResultreturn(){
if(ajaxResult){return true;}
else{
return false;
}
}
function toAjax(url,callback){
xmlhttp=new XMLHttpRequest();
/*url="http://localhost/chkname.php"; */
xmlhttp.onreadystatechange =function(){
if(xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
if(callback) {
callback(xmlhttp.responseText);
}
}
}
}
xmlhttp.open('POST',url,true);
xmlhttp.send(null);
}
function checkName(){
var name=ele.name.value;
var url="http://localhost/chkname.php";
var cb = ajaxResultdeal;
toAjax(url,cb);
}
function check(){ //表单提交则验证开始
if(ajaxResultreturn()&&checkPassw2()&&checkEmail()){
alert(" 注册成功"); //注册成功
return true;
}
else{
alert("请正确的填写完信息!");
return false;
}
}