1. 程式人生 > >Promise 封裝 Ajax 方法

Promise 封裝 Ajax 方法

var Tool = {
    ajax: function(obj) {
        return new Promise((resolve, reject) => {
            var url = obj.url || location.href;
            var type = obj.type || 'get';
            var data = this.getParam(obj.data);
            var callback = obj.callback;
            var xhr = new XMLHttpRequest();
            if (type === 'get') {
                url = url + '?' + data;
                data = null;
            }
            xhr.open(type, url);
            if (type === 'post') {
                xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
            }
            xhr.send(data);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var r = xhr.responseText;
                    //在promise中,如果想要呼叫.then中傳遞的成功的回撥
                    //只需要將當前promise標記為fulfilled
                    resolve(r);
                }
            };
        })
    },
    getParam: function(object) {
        var str = '';
        for (var k in object) {
            str += k + "=" + object[k] + "&";
        }
        str = str.substr(0, str.length - 1);
        console.log(str);
        return str;
    }
};