Ajax流程对象的创建和兼容处理(笔记)

 <button id="btn">查询</button>
  <script>
    window.onload = function() {
      var oBtn = document.getElementById('btn');
      oBtn.onclick = function() {
          var xhr = new XMLHttpRequest();//打开流浪器
          xhr.open('get','1.txt',true);//在地址栏中输入地址
          xhr.send();//提交
          xhr.onreadystatechange = function() {//等待服务器返回内容
          if(xhr.readyState == 4) {
            alert(xhr.responseText);
            responseText: Ajax请求返回的内容就被存放到这个属性下面(字符串来的)
            readyState:ajax工作的状态(有五个值,)
            onreadyStatechange(当状态值发生改变的时候,触发事件)
          }
        }
      }
    }

1、var xhr = new XMLHttpRequest() //创建ajax对象 (该对象在ie6以下有兼容性问题,ie6以下为 new ActiveXObject('Microsoft.XMLHTTP')),以下方式可以兼容ie6:

       var xhr = null;
        try {
          xhr = new XMLHttpRequest();
        }catch(e) {
          xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }
var xhr = null;
if(window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
}else {
    xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
2、open()方法有三个参数,第一个参数是打开方式、第二个参数是地址、第三个参数是指是否异步;




猜你喜欢

转载自blog.csdn.net/rose999ying/article/details/79858472