我有以下方法。
async getuserdevicesIDs() {
return await new Promise( (resolve, reject) => {
let timesDone = 0;
// tslint:disable-next-line: no-var-keyword
const viewDevicesLink = '/user/devices/view/'; // parameter: email
const xhr = new XMLHttpRequest();
// xhr.open('POST', this.AUTH_SERVER_ADDRESS + '/user/devices/view/', true);
xhr.open('POST', this.AUTH_SERVER_ADDRESS + viewDevicesLink, true);
xhr.setRequestHeader('Content-type', 'application/JSON;charset=UTF-8');
console.log(this.auth.getUserID());
const email = this.auth.getUserID().toString();
const us = new User();
us.name = '';
us.email = 'richard@gmail.com';
us.password = '';
xhr.send(JSON.stringify(us));
xhr.addEventListener('readystatechange', processRequest, false);
xhr.onreadystatechange = processRequest;
function processRequest(e) {
// tslint:disable-next-line: triple-equals
if (xhr.readyState == 4 && xhr.status == 200) {
// tslint:disable-next-line: triple-equals
if (timesDone == 0) {
// tslint:disable-next-line: prefer-const
const response = xhr.response;
timesDone++;
alert(response);
resolve(response);
}
// tslint:disable-next-line: triple-equals
} else if (xhr.readyState == 4) {
alert('server error: ' + xhr.status + ', response is: ' + xhr.responseText);
timesDone++;
return null;
}
}
});
}
此方法向服务器询问某些值,并且服务器将返回值的arrya,但我不知道如何将响应解析为arry,以供以后在此方法中使用。
this.getuserdevicesIDs().then(response => {
alert(this.IDs); })
.catch(err => {});
如果有人知道我如何将我从服务器获得的响应存储到一个数组中,这将对我有很大帮助。谢谢
答案 0 :(得分:0)
从Web服务器接收数据时,数据始终是字符串。 使用 JSON.parse()解析数据,该数据成为JavaScript对象。
resolve(JSON.parse(response));