Ajax原生写法

用太久JQuery了,别忘了Ajax原生是怎么写的

var Ajax = {
    get : function (url, callback) {

        var req = Ajax.getRequest(callback);

        req.open("GET", url, true);
        req.setRequestHeader("If-Modified-Since","0");
        req.send(null);
    },
    post : function (url, param, callback) {

        var req = Ajax.getRequest(callback);

        req.open("POST", url, true);
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        req.setRequestHeader("If-Modified-Since","0");
        req.send(param);
    },
    getRequest : function (callback) {
        var req;
        try {
            req = new XMLHttpRequest();
        } catch (error) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (error) {
                return null;
            }
        }
        req.onreadystatechange = function() {
            if (req.readyState != 4)
                return;
            if (req.status == 200) {
                callback(req);
            } else
                alert("请求失败:" + req.statusText);
            return true;
        };
        return req;
    },
    encode : function (str) {
        return encodeURIComponent(str);
    }
};

 

相关文章