原生js实现Ajax请求

参考《javascript高级程序设计》https://blog.csdn.net/ddbwjkq

function createXHR(){
    if(typeof XMLHttpRequest !="undefined"){
        return new XMLHttpRequest();
    }
    else if (typeof ActiveXObject !="undefined") {//检测原生XHR对象是否存在
       if(typeof arguments.callee.activeXString!="string"){//使用IE7以下MSXML库中的ActiveX对象创建
           var versions=[
               'MSXML2.XMLHttp.6.0',
               'MSXML2.XMLHttp.3.0',
               'MSXML2.XMLHttp'
           ],
               i,len;
           for(i=0,len=versions.length;i=200&&xhr<300)||xhr.status==304){
            alert(xhr.responseText)
        }
        else{
            alert("Request was unsuccessful:"+xhr.status);
        }
    }
};
var url="example.txt";
function addURLParam(url,name,value){//该函数用于在url中加入查询字符串
    url+=(url.indexOf("?")==-1?"?" : "&");
    url+=encodeURLComponent(name)+"="+encodeURLComponent(value);
}
url=addURLParam(url,"book","Javascript");//添加一个查询字符串
xhr.open("get",url,true);//启动一个GET请求
xhr.send(null);//发送
//--------------POST请求-------------------------
var xhr=createXHR();
xhr.onreadystatechange=function(){
    if(xhr.readyState==4){
        if((xhr.status>=200&&xhr<300)||xhr.status==304){
            alert(xhr.responseText)
        }
        else{
            alert("Request was unsuccessful:"+xhr.status);
        }
    }
};
xhr.open("post",url,true);//启动一个GET请求
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//设置表单提交的内容类型
var form=document.getElementById("user-info");
xhr.send(serialize(form));//将表单的数据序列化

 

你可能感兴趣的:(前端面试,前端,js)