Ajax技术的工作原理

 

Ajax技术核心是 XMLHttpRequest,工作原理可以分为4步

1、创建Ajax对象

var xhr = new XMLHttpRequest(); 

2、连接服务器

xhr.open('get','test.html',true);

3、发送请求

xhr.send();

4、获取响应


xhr.onreadystatechange = function(){
  if(xhr.readystate == 4){ //请求的状态码
                 /*
                   0:请求还没有建立(open执行前)
                   1:请求建立了还没发送(执行了open)
                   2:请求正式发送(执行了send)
                   3:请求已受理,有部分数据可以用,但还没有处理完成
                   4:请求完全处理完成
                 */

    alert(xhr.responseText); //返回的数据

  }
}

 下面是完整代码


function loadXMLDoc(){
  var xhr;
  if(window.XMLHttpRequest){
    xhr = new XMLHttpRequest(); //非IE浏览器创建 XMLHttpRequest 对象
  }else {
    xhr = new ActiveObject("Microsoft.XMLHTTP"); //IE浏览器创建 XMLHttpQuest 对象
  }
  
  xhr.open('get','test.html',true);
  xhr.send();
  
  xhr.onreadystatechange = function(){  
    if(xhr.readyState == 4 && xhr.status == 200){
      document.getElementById("myDiv").innerHTML = xhr.reponseText;
    }
  }
}

 

posted @ 2019-07-16 16:34  足迹#  阅读(378)  评论(0编辑  收藏  举报