Promise封装_AJAX

2019-12-15  本文已影响0人  learninginto

Promise封装_AJAX

beautiful.jpg
function ajax(url, options) {
    return new Promise(function (resolve, reject) {
        // 拼接options.data;
        var temp_data = "";
        if (typeof options.data === "object") {
            // console.log(options.data);
            for (var attr in options.data) {
                temp_data += (temp_data ? "&" : "") + attr + "=" + options.data[attr]
            }
        }
        options.type == "GET" ? url += (/\?/.test(url) ? "&" : "?") + temp_data : "";
        var xhr = new XMLHttpRequest();
        xhr.open(options.type ? options.type : "GET", url);
        options.type === "POST" ? xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;") : "";
        xhr.send(options.type === "POST" ? temp_data : null);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                resolve(xhr.responseText);
                typeof options.callback === "function" ? options.callback(xhr.responseText) : "";
            }
        }
    })

}
ajax("./server/post.php", {
      type: "POST",
      data: {
            key: "value"
      },
      callback: function (res) {
            console.log(res);
      }
}).then(function (res) {
      console.log(res);
})
上一篇下一篇

猜你喜欢

热点阅读