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