ajax的实现,基于XHR的原理

function createXHR(){
    if (typeof XMLHttpRequest != "undefined"){
        return new XMLHttpRequest(); //IE8及以上和其他浏览器,不管IE6,IE7这段就行了
    } else if (typeof ActiveXObject != "undefined"){
        if (typeof arguments.callee.activeXString != "string"){
            var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0",
                            "MSXML2.XMLHttp"],
                i, len;
    
            for (i=0,len=versions.length; i < len; i++){
                try {
                    var xhr = new ActiveXObject(versions[i]);
                    arguments.callee.activeXString = versions[i];
                    return xhr;
                } catch (ex){
                    //skip
                }
            }
        }
    
        return new ActiveXObject(arguments.callee.activeXString);
    } else {
        throw new Error("No XHR object available.");
    }
}

var xhr = createXHR();  
// onreadystatechange必须写在open()方法之前     
xhr.onreadystatechange = function(event){
    if (xhr.readyState == 4){//4代表响应已经完全加载
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
            alert(xhr.responseText);
        } else {
            alert("Request was unsuccessful: " + xhr.status);
        }
    }
};
xhr.open("get", "example.txt", true);//不是真正发送请求,而是启动一个请求以备发送
//setRequestHeader必须写在open和send中间
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("MyHeader", "MyValue");//自定义头部
xhr.send(null);//发送传递的参数,get方式一般传null,参数用encodeURIComponent转码后跟在url后面,参数名和值都要


//post方式可以有几下几种方式提交数据

var form = document.getElementById("user-info");  
1、xhr.send(serialize(form));          
2、xhr.send(new FormData(form));
3、xhr.send(new FormData().append("myName","myValue"));

你可能感兴趣的:(javascipt,Js)