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

对onreadystatechange属性的理解

发布时间:2020-12-16 05:49:00 所属栏目:百科 来源:网络整理
导读:var xmlHttp;//创建一个XmlHttpRequeset对象function createXMLHttpRequest(){ if(window.ActiveXObject){ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest){ xmlHttp = new XMLHttpRequest(); }}//开始一个请求functio
var xmlHttp;
//创建一个XmlHttpRequeset对象
function createXMLHttpRequest(){
    if(window.ActiveXObject){
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest){
        xmlHttp = new XMLHttpRequest();
    }
}
//开始一个请求
function startRequest(){
    
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handlestatechange;
    xmlHttp.open("GET","SimpleRespose.xml",true);
    xmlHttp.Send(null);
} 

function handlestatechange(){
    if(xmlHttp.readyState == 4){//描述一种"已加载"状态;此时,响应已经被完全接收。
        if(xmlHttp.status == 200){//200表示成功收到        
            alert("The Server Replied with:" + xmlHttp.responseText)
        }
    }
}            
xmlHttp.onreadystatechange指向了一个函数,这个函数是在 xmlHttpRequest.readyState发生改变的时候触发。我们再来看startRequest函数,想象一下整个请求发送的步骤。现在我们点击一个按钮,触发了一个startRequest函数。函数往下走,第一步是createXmlHttpRequest(),它的作用是创建一个 xmlHttpRequest对象,当它完毕的时候,xmlHttpRequest.readyState的值是0(window.alert跟踪得到的),程序继续往下走,xmlHttp.onreadystatechange = handlestatechange,因为状态没有改变(xmlHttpRequest.readyState的值是0),所以不触发函数,紧接着是 Open()和Send(),那么,整个函数从头到尾都应该没有触发handlestatechange函数啊,但是为什么出来的结果是正确的呢?

后来我用window.alert跟踪xmlHttp.readystate的变化,发现于原来它运行的机制是这样的。首先创建一个 xmlHttpRequest的对象之后xmlHttp.readyState的值是0了,然后xmlHttp.onreadystatechange = handlestatechange没有运行。紧接着是open(),这个函数发生了之后xmlHttp.readyState的值是1了,那么就会有一个断点在Open()函数处断开,保留现场,紧接着又返回到xmlHttp.onreadystatechange = handlestatechange运行,然后再执行Send()函数,这个函数发生了之后xmlHttp.readyState的值是2了,接着又返回到xmlHttp.onreadystatechange = handlestatechange运行。以此类推。


??

(编辑:李大同)

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

    推荐文章
      热点阅读