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