ajax原理笔记


function AJAX() {

    var xhr = null;

    if(window.XMLHttpRequest) {

        xhr = new XMLHttpRequest();

    } else {

        try{

            xhr = new ActiveXObject('Microsoft.XMLHttp');

        }catch(e){

            xhr = new ActiveXObject('msxml2.xmlhttp');

        }

    }

    //get请求

    this.get = function(url,success,fail){

        xhr.open("GET", url,true);

        xhr.onreadystatechange=function(){

            if(xhr.readyState==4) {

                if(xhr.status==200) {

                    var txt = xhr.responseText;

                    txt = JSON.parse(txt);

                    success(txt);

                } else {

                    if(fail) {

                        fail(xhr.status);

                    }

                }

            }

        };

        xhr.send(null);

    };

    //post请求

    this.post = function (url,param,success,fail) {

        xhr.open("POST", url,true);

        xhr.onreadystatechange=function(){

            if(xhr.readyState==4) {

                if(xhr.status==200) {

                    var txt = xhr.responseText;

                    txt = JSON.parse(txt);

                    success(txt);

                } else {

                    if(fail) {

                        fail(xhr.status);

                    }

                }

            }

        };

        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        xhr.send(param);

    };

}

//使用

var ajax = new AJAX();

ajax.get("test.json",

function(data){

    //成功回调

},function(data){

//失败回调

});

你可能感兴趣的:(ajax原理笔记)