baby-zuji

 

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;
    }
  }
}

 

分类:

技术点:

相关文章:

  • 2021-11-05
  • 2021-11-05
  • 2021-11-04
  • 2021-11-06
  • 2021-11-04
猜你喜欢
  • 2021-12-18
  • 2021-11-02
  • 2021-05-25
  • 2022-01-06
  • 2021-11-28
  • 2021-09-09
  • 2021-06-14
相关资源
相似解决方案