我有一个费用表单,可以将数据保存到浏览器本地存储中。我在表格下方的页面上有邻居,这样在您填写表格后,您可以点击以便以良好的格式打印出数据。
由于我的应用程序的功能,我必须在本地存储中使用JSON数据。
我使用js变量从本地存储中获取数据:
var my_expenses = localStorage.getItem('my_expenses');
这是我的浏览器本地存储中的条目,具有未确定的值。
键:my_expenses 值:
{
"income": {
"1": {
"name": "Pay (after tax)",
"freq": "26",
"value": "233"
},
"2": {
"name": "Partners take home pay",
"freq": "4",
"value": "10"
},
"3": {
"name": "Bonuses/overtime",
"freq": "26",
"value": "30"
},
"4": {
"name": "Income from savings and investments",
"freq": "1",
"value": "50"
},
"5": {
"name": "Child support received ",
"freq": "12",
"value": "40"
}
},
"outgoings": {
"1": {
"name": "Electricity",
"freq": "4",
"value": "0"
},
"2": {
"name": "Gas",
"freq": "4",
"value": "0"
},
"3": {
"name": "Water",
"freq": "4",
"value": "0"
},
"4": {
"name": "Internet",
"freq": "4",
"value": "0"
},
"5": {
"name": "Telephone",
"freq": "4",
"value": "0"
},
"6": {
"name": "Car Insurance",
"freq": "1",
"value": "0"
}
}
}
根据Print.js,您可以像这样打印JSON数据(包括我的本地存储数据的变量):
<button type="button" onclick="printJS({printable: my_expenses, properties: ['name', 'freq', 'value'], type: 'json'})">
Print JSON Data
出于某种原因,我在控制台中收到错误,我无法弄明白,也没有打开对话框进行打印。
Uncaught Error: Missing printable information.
at init (print.min.js:1)
at HTMLButtonElement.onclick ((index):156)
我认为它可能是我在本地存储中的JSON结构?任何帮助都会深深感激。
尝试使用JSON.parse(),如下所示:
var my_expenses = JSON.parse(localStorage.getItem("my_expenses"));
在我添加JSON解析之前。我收到了警告,这是控制台中本地存储的输出。
我添加后,这是输出,打印按钮似乎工作:
但是打印对话没有数据?
如何创建对象和本地存储功能:
//Set the default incomes and outgoings here
var defaultsObj = {
'income':{
1:{name:"Pay (after tax)",freq:52,value:0},
2:{name:"Partners take home pay",freq:4,value:0},
3:{name:"Bonuses/overtime",freq:26,value:0},
4:{name:"Income from savings and investments",freq:1,value:0},
5:{name:"Child support received ",freq:12,value:0}
},'outgoings':{
1:{name:"Electricity",freq:4,value:0},
2:{name:"Gas",freq:4,value:0},
3:{name:"Water",freq:4,value:0},
4:{name:"Internet",freq:4,value:0},
5:{name:"Telephone",freq:4,value:0},
6:{name:"Car Insurance",freq:1,value:0}
}
};
//Functions to store and retrieve objects from localstorage
function ls_store(name,o){
localStorage.setItem(name, JSON.stringify(o));
};
function ls_read(name){
return JSON.parse(localStorage.getItem(name));
};
function set_defaults(){
ls_store('my_expenses',defaultsObj);
expensesObj = ls_read('my_expenses');
}
//If our localstroage items are empty let's store the defaults
if(ls_read('my_expenses')==null){
set_defaults();
}
答案 0 :(得分:2)
你不保存数组,printjs等待数组。
尝试保存为两个不同的数组,首先,将结果显示在pdf中。
如果显示第一个数组的数据,你必须:调用两次printjs,一个用于第一个数组,另一个用于第二个数组,或者将这两个数组合成一个数组,如果是incombe或结果,可以添加atisting到disting。