[Angular2+]POST/formData/XMLHttpRequest/获取responseText/Promise

angular怎么发送formData

怎么写原生的xhr

写了xhr发现是异步的取不到返回值怎么办

解决方法:用Promise包装,把返回值resolve即可

 sendPost(url) {const xhr = new XMLHttpRequest();const data = JSON.stringify(this.buildPostData())return new Promise(function (resolve, reject) {xhr.open('POST', url, true);const formData: FormData = new FormData();console.log(data, formData);formData.append('config', data);xhr.onload = function () {if (xhr.readyState == XMLHttpRequest.DONE) {resolve(xhr.responseText);}}xhr.onerror = reject;xhr.send(formData);});}async save() {let res = await this.sendPost(this.site.apiUrl + '/Config/setConfigAsync');console.log("save", res);setTimeout(() => {if (res === "1") {this.alertSuccess = true;}else {this.alertError = true;}}, 500);setTimeout(() => {this.alertSuccess = false;this.alertError = false;}, 3000);}

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部