我已经根据此站点上的其他问题尝试了多种变体,但似乎无法将响应正确映射到阵列中。
尝试使用/不使用JSON.Parse,尝试在GET标头中使用responseType:'json',尝试使用response和response.data
function getNotificationsForDevice() {
var MAC_ADDRESS = document.getElementById("DeviceInput").value;
var regexp = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}[,]?)+$/i;
var DeviceAlertE = document.getElementById("DeviceAlert");
var notifications = [];
if (regexp.test(MAC_ADDRESS)) {
axios
.get("http://localhost:56005/api/Notifications", {
//responseType: 'json',
params: {
MacAddress: MAC_ADDRESS
}
})
.then(res => {
const newNotification = {
id : res.data.ID,
destination : res.data.Destination,
MacAddress : res.data.MAC_ADDRESS
};
notifications.push(newNotification);
})
.catch(function(error) {
console.log(error);
});
DeviceAlertE.innerHTML = "";
} else {
alert("Invalid MAC Address");
}
localStorage.setItem("notifications", JSON.stringify(notifications));
fetchNotifications();
}
notifications数组始终为空,而不是从GET中获取数据。
编辑: 获取如下所示的回复
0:{…} 目的地:“ email1@gmail.com” ID:1 MacAddress:“ f8:f0:05:ed:1d:28” SendAlertTypes:“ 0,1,2,3,4,5,6” :对象{…} 1:{…} 目的地:“ email2@hotmail.com” 编号:6 MacAddress:“ f8:f0:05:ed:1d:28” SendAlertTypes:“ 0,1,2,3,4,5,6” :对象{…} 2:{…} 目的地:“ email3@vtext.com” ID:14 MacAddress:“ f8:f0:05:ed:1d:28” SendAlertTypes:“ 0,1,2,3,4,5,6” :{…
答案 0 :(得分:1)
您要在实际填充通知数组之前将其保存在localStorage中。您应该执行以下操作:
function getNotificationsForDevice() {
var MAC_ADDRESS = document.getElementById("DeviceInput").value;
var regexp = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}[,]?)+$/i;
var DeviceAlertE = document.getElementById("DeviceAlert");
var notifications = [];
if (regexp.test(MAC_ADDRESS)) {
axios
.get("http://localhost:56005/api/Notifications", {
//responseType: 'json',
params: {
MacAddress: MAC_ADDRESS
}
})
.then(res => {
const newNotification = {
id : res.data.ID,
destination : res.data.Destination,
MacAddress : res.data.MAC_ADDRESS
};
notifications.push(newNotification);
// Moved code here so you have the notifications array with your request's data
localStorage.setItem("notifications", JSON.stringify(notifications));
fetchNotifications();
})
.catch(function(error) {
console.log(error);
});
DeviceAlertE.innerHTML = "";
} else {
alert("Invalid MAC Address");
}
}
答案 1 :(得分:0)
我正在尝试将作为数组的共振映射到我的数组中。我最终循环响应以获取填充单个对象然后推送到数组所需的数据。