JavaScript写一个Ajax

  • js实现ajax

js实现ajax

var xmlHttpReq = null;
if(window.ActiveXObject) {
    xmlHttpReq = new ActiveXObject('Microsoft.XMLHTTP');
} else if(window.XMLHttpRequest) {
    xmlHttpReq = new XMLHttpRequest();
}
xmlHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpReq.open('GET','test.php',true);
xmlHttpReq.onreadystatechange = function(){
    if(xmlHttpReq.readyState === 4) {
        if(xmlHttpReq.status === 200) {
            alert(xmlHttpReq.responseText);
        }
    }
};
xmlHttpReq.send(null);

例子如下:

submit.onclick = function(){
    var xmlHttpReq = null;
    if(window.ActiveXObject) {
        xmlHttpReq = new ActiveXObject('Microsoft.XMLHTTP');
    } else if(window.XMLHttpRequest) {
        xmlHttpReq = new XMLHttpRequest();
    }
    xmlHttpReq.open('POST','http://10.2.229.82:8088/api/friend',true);
    xmlHttpReq.onreadystatechange = function(){
        if(xmlHttpReq.readyState === 4) {
            if(xmlHttpReq.status === 200) {
                alert(xmlHttpReq.responseText);
            }
        }
    };
    xmlHttpReq.send("a=1,b=2");
};

如果要设置请求头的话:

submit.onclick = function(){
    var xmlHttpReq = null;
    if(window.ActiveXObject) {
        xmlHttpReq = new ActiveXObject('Microsoft.XMLHTTP');
    } else if(window.XMLHttpRequest) {
        xmlHttpReq = new XMLHttpRequest();
    }

    xmlHttpReq.open('POST','http://10.2.229.82:8088/api/friend',true);
    xmlHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
    xmlHttpReq.onreadystatechange = function(){
        if(xmlHttpReq.readyState === 4) {
            if(xmlHttpReq.status === 200) {
                alert(xmlHttpReq.responseText);
            }
        }
    };
    xmlHttpReq.send("a=1,b=2");
};

你可能感兴趣的:(前端)