我无法在本地存储中保存数据,我得到结果 [object Object],[object Object],[object Object]
这是代码
var usersonline = null;
var maxonline = 50;
Highcharts.stockChart('container', {
chart: {
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.round(usersonline);
series.addPoint([x, y], true, false);
}, 1000);
}
}
},
time: {
useUTC: false
},
rangeSelector: {
buttons: [{
count: 1,
type: 'hour',
text: '1H'
}, {
count: 3,
type: 'hour',
text: '3H'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 2
},
title: {
text: 'Live Chart of Players Online'
},
exporting: {
enabled: false
},
yAxis: {
title: 'Players Online',
min: 0,
plotLines: [{
color: 'red', // Color value
label: {
text: "Max Player Line"
},
value: maxonline, // Value of where the line will appear
width: 2 // Width of the line
}]
},
series: [{
name: 'Players Online',
connectNulls: false,
data: (function () {
var data = [],
time = (new Date()).getTime(),
i;
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem("chartdata") === null) {
localStorage.setItem('chartdata',[])
data = []
console.log("No Data Found, Creating Some!")
} else {
data = JSON.parse(localStorage.getItem('chartdata'))
console.log("Chart Data Loaded.")
}
} else {
console.log("localStorage is not Supported. Saving Chart Data will not work.")
}
// generate an array of random data
window.onbeforeunload = function(){
console.log("Chart data Saved")
localStorage.chartdata = JSON.stringify(data)
}
return data;
}())
}],
lang: {
noData: "No Data."
},
noData: {
style: {
fontWeight: 'bold',
fontSize: '40px',
color: '#303030'
}
}
});
如果我刷新页面,它会将图表显示为空白,并且不会显示“无数据”,所以那里有数据但已损坏。我想要发生的是当我刷新页面时它会保留数据,即使浏览器或计算机重新启动也是如此。
这个问题有什么解决办法吗,我试了很多方法都没用。
这是一个实时数据图表,我需要保存数据,这样如果您不小心刷新页面,图表就不会变成空白。
最佳答案
所以当你得到项目时它说 [Object object]
的原因是因为 localStorage.setItem
接受一个 DOMString
,而不是一个目的。 setItem
将使用 toString
将值强制转换为字符串,而 Object.prototype.toString
将始终为 [object Object]
.
https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem
您需要在 localStorage.setItem
函数调用中使用 JSON.stringify
将数组转换为有效的 JSON 字符串,然后使用 JSON.parse
在您使用 localStorage.getItem
时解析该字符串。
const loki = { "type": "dog", "name": "Loki" }
// Sets [object Object] in local storage
localStorage.setItem("lokiKey", loki)
// Sets "{"type":"dog","name":"Loki"}" in local storage
localStorage.setItem("lokiKey", JSON.stringify(loki))
希望这对您有所帮助!
关于javascript - 我无法将 highchart 图表数据保存在 localStorage 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62822909/