Promise封装_AJAX

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);
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容