JavaScript series using promise encapsulation Ajax

Source: Internet
Author: User
Invoke function ajax ({URL: ' Your request URL ', method: ' Get ', async:true, timeout:1000,
        Data: {test:1, Aaa:2}}). Then (res => console.log (' Successful request: ' + res '), Err => Console.log (' request failed: ' + err ')//focus ...  Functions encapsulate 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 (' request timeout ') Xhr.onreadystatechange = () => {if (xhr.readystate = 4) { if (xhr.status >= && xhr.status < $ | | xhr.status = 304) {Resolve && Resolve (Xhr.responsetext)} else { Reject && reject ()}} xhr.onerror = Err => R Eject && reject (err) let Paramarr = [] Let Encodedata if (data instanceof OBJ
                    ECT) {for (let key in data) {//parameter stitching needs to be encoded by encodeuricomponent Paramarr.push (encodeURIComponent (key) + ' = ' + encodeURIComponent (data[key))} Encodeda
                Ta = Paramarr.join (' & ')} if (method = = to ' get ') {//detect if the URL already exists? and its location
                Const INDEX = Url.indexof ('? ')
                if (index = = = 1) url = '? ' 

            else if (index!== url.length-1) url = ' & '//Splice URL = + Encodedata} Xhr.open (method, URL, async) if (method = = = ' Get ') xhr.send (null) else {//Post mode requires setting the request header XH
            R.setrequestheader (' Content-type ', ' Application/x-www-form-urlencoded;charset=utf-8 ') xhr.send (EncodeData) }
        } )
    }
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.