javascript系列之使用Promise封裝ajax

來源:互聯網
上載者:User
//調用函數 ajax({        url: 'your request url',        method: 'get',        async: true,        timeout: 1000,        data: {            test: 1,            aaa: 2        }    }).then(        res => console.log('請求成功: ' + res),        err => console.log('請求失敗: ' + err)    )    //重點。。。函數封裝function ajax (options) {        let url = options.url        const method = options.method.toLocaleLowerCase() || 'get'        const async = options.async != false // default is true        const data = options.data        const xhr = new XMLHttpRequest()        if (options.timeout && options.timeout > 0) {            xhr.timeout = options.timeout        }        return new Promise ( (resolve, reject) => {            xhr.ontimeout = () => reject && reject('請求逾時')            xhr.onreadystatechange = () => {                if (xhr.readyState == 4) {                    if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {                        resolve && resolve(xhr.responseText)                    } else {                        reject && reject()                    }                }            }            xhr.onerror = err => reject && reject(err)            let paramArr = []            let encodeData            if (data instanceof Object) {                for (let key in data) {                    // 參數拼接需要通過 encodeURIComponent 進行編碼                    paramArr.push( encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) )                }                encodeData = paramArr.join('&')            }            if (method === 'get') {                // 檢測 url 中是否已存在 ? 及其位置                const index = url.indexOf('?')                if (index === -1) url += '?'                else if (index !== url.length -1) url += '&'                // 拼接 url                url += encodeData            }            xhr.open(method, url, async)            if (method === 'get') xhr.send(null)            else {                // post 方式需要佈建要求頭                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8')                xhr.send(encodeData)            }        } )    }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.