纯手写AJAX

function ajax(){  
    //http相应对象
    var xmlhttp;  
    //判断浏览器
    if(window.XMLHttpRequest){  
        xmlhttp = new XMLHttpRequest();  
    }else{  
        // code for IE6, IE5  
        xmlhttp = ActionXObject("Microsoft.XMLHTTP");  
    }  
      
    //判定执行状态  
    xmlhttp.onreadystatechange = function(){  
        /* 
        readyState 
            0: 请求未初始化 
            1: 服务器连接已建立 
            2: 请求已接收 
            3: 请求处理中 
            4: 请求已完成,且响应已就绪 
        status 
            200:请求成功 
            404:未找到 
            500:服务器内部错误 
        */  
        if (xmlhttp.readyState==4 && xmlhttp.status==200){  
            document.getElementById("myDiv").innerHTML=xmlhttp.responseText;//获得字符串形式的响应数据,如果返回的是XML需要单独解析  
            //responseXML       获得 XML 形式的响应数据  
            var xmlDoc = xmlhttp.responseXML;  
            var txt = "";  
            var num = xmlDoc.getElementsByName("value");//获取节点name=value的值  
            for(var i=0;i<num.length;i++){  
                txt = txt+num[i].childNodes[0].nodeValue+"<br />";  
            }  
            document.getElementById("myDiv2").innerHTML = txt;  
        }  
    }  
      
    //@param 最后一个参数表示是否是异步提交,为了避免使用缓存我们加上一个时间戳  
    xmlhttp.open("Get","url"+  
        (function(){  
            var date = new Date();  
            return date.getSeconds();     
        })  
    ,true);  
      
    //设置头信息  
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");  
      
    //将信息发送到服务器  
    xmlhttp.send();   
      
}  
原文地址:https://www.cnblogs.com/zlero/p/4358909.html