美文网首页
ajax原生兼容

ajax原生兼容

作者: 幸福幸福幸福 | 来源:发表于2017-01-05 18:31 被阅读151次

总结一下JavaScript原生ajax写法

有get和post两种方法,写法差异不大

POST方法:

    // 1.创建XMLHttpRequest对象
    var xmlhttp;if(window.XMLHttpRequest){  
     //适用于IE7、IE8、FireFox、Opera等浏览器   
    xmlhttp = new XMLHttpRequest();   
    if(xmlhttp.overrideMineType){
          xmlhttp.overrideMineType("text/xml")
       }
    }else if(window.ActiveXObject){
       //IE6、IE5、IE5.5
       var activexName = ["MSXML2.XMLHTTP","Miscrosoft.XMLHTTP"];                 
     for(var i =0 ;i<activexName.length;i++){
          try{
             xmlhttp = new ActiveXObject(activexName[i]);
          }catch(e){
                   }
       }
    }else if(xmlhttp == undefind || xmlhttp == null){
       alert("当前浏览器不支持创建XMLHttpRequest对象");
      }

    // 2.配置 (请求方式,请求地址,同步/异步)
     xmlhttp.open('POST', '5.php', true);

    // 3.发送
    // 当进行post数据传递的时候,需要setRequestHeader设置头信息
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");    //请求json文件时:"application/json"
    xmlhttp.send('id=24');

    //4. 监测(必须放在new和open之间)
    xmlhttp.onreadystatechange = function(){   
    // readyState == 4 和 status == 200
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          // 接收返回的文本
          alert(xmlhttp.responseText);
       }
    }

GET方法

    // 1.创建XMLHttpRequest对象
    var xmlhttp;if(window.XMLHttpRequest){
       //适用于IE7、IE8、FireFox、Opera等浏览器
       xmlhttp = new XMLHttpRequest();
       if(xmlhttp.overrideMineType){      
            xmlhttp.overrideMineType("text/xml")
       }
    }else if(window.ActiveXObject){
       //IE6、IE5、IE5.5
       var activexName = ["MSXML2.XMLHTTP","Miscrosoft.XMLHTTP"];
       for(var i =0 ;i<activexName.length;i++){
          try{
                 xmlhttp = new ActiveXObject(activexName[i]);
               }catch(e){
               }
       }
    }else if(xmlhttp == undefind || xmlhttp == null){
       alert("当前浏览器不支持创建XMLHttpRequest对象");
    }

    // 2.配置
    xmlhttp.open('GET', '4.php?id=30', true);    // true异步

    // 3.发送
    xmlhttp.send();

    // 4.时时刻刻监测XMLHttpRequest对象的进展情况
    /*readyState:
      0:请求未初始化
      1:请求已经建立
      2:请求已接收   
      3:请求以处理   
      4:请求处理结束(*)
      status:   200:网络请求成功
      404:找不到对应的页面*/
      xmlhttp.onreadystatechange = function(){
          if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
             // 请求成功
             alert(xmlhttp.responseText);
          }
       }

相关文章

网友评论

      本文标题:ajax原生兼容

      本文链接:https://www.haomeiwen.com/subject/ueizvttx.html