加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax中同步与异步的一个小区别

发布时间:2020-12-16 01:02:46 所属栏目:百科 来源:网络整理
导读:第一种情况:异步请求:xhr.open('post','check_name.do',true); function check_name(){ var flag=false; xhr.open('post',true); xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange=function(){ if(xhr

第一种情况:异步请求:xhr.open('post','check_name.do',true);

function check_name(){

var flag=false;
xhr.open('post',true);
xhr.setRequestHeader('content-type',
'application/x-www-form-urlencoded');
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
var txt=xhr.responseText;
document.getElementById("username_msg").innerHTML=txt;
flag=true;
}
};
xhr.send('username='+text);

alert(flag);

returnflag;

这里alert(flag)的结果为false,return返回为false。程序依次执行,不会等待从服务器返回后执行状态处理函数的


第二种情况:同步请求xhr.open('post',false);

这里alert(flag)的结果为true,return返回为true。执行了xhr.send()之后,再等待从服务器返回后执行状态处理函数,然后执行return


一般在等待表单验证登录时,可以采用同步请求方式,通常情况下都用异步请求方式。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读