Using the Promise encapsulation simple Ajax method __ajax

Source: Internet
Author: User

Always enjoy using native JavaScript, especially if you don't need to consider compatibility scenarios (albeit pitifully). Unfortunately ECMAScript does not encapsulate a good Ajax method (in fact, there is no need to have), the use of their own promise a bar. Get

function Getjson (URL) {return
    new Promise (Resolve, Reject) => {
        var xhr = new XMLHttpRequest ()
        Xhr.open (' Get ', url, true)

        Xhr.onreadystatechange = function () {
            if (this.readystate = = 4) {
                if (this.status = =) {
                    Resolve (this.re Sponsetext, this)
                } else {
                    var Resjson = {code:this.status, response:this.response}
                    reject (Resjson, this }}}

        xhr.send ()}
    )

}
POST
function Postjson (URL, data) {return
    new Promise (Resolve, Reject) => {
        var xhr = new XMLHttpRequest ()
        XH R.open ("POST", url, True)
        Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");

        Xhr.onreadystatechange = function () {
            if (this.readystate = = 4) {
                if (this.status = =) {
                    Resolve (JSON.PA RSE (This.responsetext), this)
                } else {
                    var Resjson = {code:this.status, response:this.response}
                    reject (r Esjson, this)}}

        xhr.send (json.stringify (data)
    })
}

In fact, promise is a natural try...catch

Getjson ('/api/v1/xxx ')    //=> This is just a try
. catch (Error => {/
  /dosomething          //=> Here is the catch to the error, if handling the error and returning the appropriate value
})
. Then (value => {
  //dosomething//          here is final
})

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.