ajax函数返回值,ajax:怎么获得onreadystatechange调用的函数的返回值?

本文深入探讨了异步Ajax的工作原理,强调了由于其非同步性质,不能直接获取返回值,而是通过回调函数来处理响应。文中通过示例展示了如何在注册表单验证中使用Ajax进行用户名检查,并解释了如何利用回调函数处理验证结果,确保表单提交前的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

异步的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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值