美文网首页
Promise封装_AJAX

Promise封装_AJAX

作者: learninginto | 来源:发表于2019-12-15 23:31 被阅读0次

    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);
    })
    

    相关文章

      网友评论

          本文标题:Promise封装_AJAX

          本文链接:https://www.haomeiwen.com/subject/fwtrnctx.html