手寫一個簡單的ajax

window.Ajax = {
        get: function (url, fn) {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) {
                    fn.call(this, xhr.responseText);
                }
            };
            xhr.send();
        },
        post: function (url, data, fn) {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
                    fn.call(this, xhr.responseText);
                }
            };
            xhr.send(data);
        },
        jsonp: function (obj) {
            window["callback"] = function (res) {
                res = typeof res === 'string' ? JSON.parse(res) : res;
                obj.success(res);
            }
            var script = document.createElement("script");
            script.src = obj.url;
            for (key in obj.data) {
                script.src += "&" + key + "=" + obj.data[key];
            }
            document.getElementsByTagName("body")[0].appendChild(script);
        }
    }複製代碼
相關文章
相關標籤/搜索