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