【问题标题】:How to store data after refreshing the web page?刷新网页后如何存储数据?
【发布时间】:2019-09-30 18:49:50
【问题描述】:

所以我构建了一个应用程序来跟踪我的每月预算 - 费用、收入、百分比等。我在这里试图解决的问题是,当我将我的项目添加到用户界面(前端)时我希望他们在我重新加载页面后保留总预算,因为现在他们在 HTML 代码中有值,我将其更改为零。有人告诉我这里与 JSON 有关,但我不知道如何使用它。如果有人可以帮助我,将不胜感激。我无法粘贴整个代码,因为它是 450 行 javascript。

我尝试了不同的方法,但都没有奏效。

// GLOBAL APP CONTROLER
var controller = (function(budgetCtrl, UICtrl) {

    var setupEventListeners = function() {
        var DOM = UICtrl.getDOMstrings();

        document.querySelector(DOM.inputBtn).addEventListener('click', ctrlAddItem);

        document.addEventListener('keypress', function(event) {
            if (event.keyCode === 13 || event.which === 13) {

                ctrlAddItem();

            }
        });

        document.querySelector(DOM.container).addEventListener('click', ctrDeleteItem);

        document.querySelector(DOM.inputType).addEventListener('change', UICtrl.changedType);
    };

    var updateBudget = function() {

        // 1. Calculate the budget
        budgetCtrl.calculateBudget();

        // 2. Return Budget
        var budget = budgetCtrl.getBudget(); // the getBudget method only returns the budget,inc,exp and %

        // 3. Display the budget on the UI
        UICtrl.displayBudget(budget);
    };

    var updatePercentages = function() {
        // 1. Calculate the percentages
        budgetCtrl.calculatePercentages();

        // 2. Read percentages from budget controller
        var percentages = budgetCtrl.getPercentages();

        // 3. Display the percentages on the UI
        UICtrl.displayPercentages(percentages);
    };

    var ctrlAddItem = function () {
        var input, newItem;

        // 1. Get the field input data
        input = UIController.getInput();

        // we check if there is an input description or value so the code runs
        if (input.description !== '' && !isNaN(input.value) && input.value > 0) {
            // 2. Add the item to the budget controler
            newItem = budgetCtrl.addItem(input.type, input.description, input.value);

            // 3. Add the new item to the UI
            UICtrl.addListItem(newItem, input.type);

            // 4. Clear the fields
            UICtrl.clearFields();

            // 5. Calculate and update Budget
            updateBudget();

            // 6. Calculate and update percentages
            updatePercentages();
        }
    };

    var ctrDeleteItem = function(event) {
        var itemID, splitID, type, ID;

        itemID = event.target.parentNode.parentNode.parentNode.parentNode.id; // parentNode gets the parent of the target of the event

        if (itemID) {

            // inc-1
            splitID = itemID.split('-'); // split returns an array with the other items except the '-'
            type = splitID[0];
            ID = parseInt(splitID[1]);

            // 1. Delete the item from the data structure
            budgetCtrl.deleteItem(type, ID);

            // 2. Delete the item from the UI
            UICtrl.deleteListItem(itemID);

            // 3. Update and show the new budget
            updateBudget();

            // 4. Calculate and update percentages
            updatePercentages();
        }

    };

    return {
        init: function() {
            console.log('Application has started.');
            UICtrl.displayMonth();
            // 3. Display the budget on the UI
            UICtrl.displayBudget({
                budget: 0,
                totalInc: 0,
                totalExp: 0,
                percentage: -1
            });
            setupEventListeners();
        }
    }


})(budgetController, UIController);;

我目前将数据存储在数据控制器中

// BUDGET CONTROLLER
var budgetController = (function() {

    // we create a constructor 
    var Expense = function(id, description, value) {
        this.id = id;
        this.description = description;
        this.value = value;
        this.percentage = -1;
    };

    // this method in the prototype of expense calculates %
    Expense.prototype.calcPercentage = function(totalIncome) {

        if (totalIncome > 0) {
            this.percentage = Math.round((this.value / totalIncome) * 100); 
        } else {
            this.percentage = -1
        }
    };

    // this method in the prototype of expense returns the %
    Expense.prototype.getPercentage = function() {
        return this.percentage;
    };

    var Income = function(id, description, value) {
        this.id = id;
        this.description = description;
        this.value = value;
    };

    var calculateTotal = function(type) {
        var sum = 0;
        data.allItems[type].forEach(function(cur) {
            sum += cur.value;
        });
        data.totals[type] = sum;
    };

    // we store the incomes' description in all items array and the price in the totals
    var data = {
        allItems: {
            exp: [],
            inc: []
        },
        totals: {
            exp: 0,
            inc: 0
        },
        budget: 0,
        percentage: -1
    };

【问题讨论】:

  • 目前,你在哪里存储值?
  • 您尝试过 Web 会话或本地存储吗?
  • 我目前将值存储在数据控制器中

标签: javascript html css json


【解决方案1】:

尝试localstorage 存储数据

localStorage.setItem('test', 1);
alert( localStorage.getItem('test') );

【讨论】:

  • 你能帮我做一些更具体的事情吗?我在上面提供了更多代码。
【解决方案2】:

为您提供一些选择:

  1. 您可能希望将数据存储在某种形式的服务器端存储中。你如何做到这一点对于一个 SO 答案来说太宽泛了。

  2. 可以使用基于浏览器的存储 (localStorage),请注意,如果您“清除浏览数据”,这些数据将属于您要清除的内容之一。

  3. 您还可以将数据存储在您上传到页面然后从页面下载的文件中。

对于#2 和#3,您可能希望使用JSON 作为您的存储格式。我将从#2 开始,然后讨论如何将其调整为#3:

在页面加载时,您将加载并解析来自localStorage 的数据:

var data = JSON.parse(localStorage.getItem("yourData")) ||  {
   thisFigure: 0,
   thatFigure: 0,
   theOtherFigure: 0
};

|| {/*...*/} 部分在数据不存在时首次提供默认值。

每次更改某些内容时,都会将数据保存到localStorage

localStorage.setItem("yourData", JSON.stringify(data));

现在,如果您想将其存储在可以上传到您的页面并从您的页面下载的文件中,您需要使用FileReader 进行上传,通过readAsText 读取数据,然后使用@987654333 @ 如上所述。要创建要下载的文件,您将创建一个 Blob 包含来自 JSON.stringify 的 JSON 字符串(链接的 MDN 页面显示如何执行此操作)并将其作为链接提供,然后单击并保存到您的本地磁盘。

【讨论】:

    【解决方案3】:

    您可以使用浏览器的本地存储。它适用于大多数现代浏览器

    localStorage.setItem('Key', "Value");
    let k = localStorage.getItem('Key');
    

    【讨论】:

      【解决方案4】:

      您可以使用localStorage在客户端存储数据。

      例如:

      localStorage.setItem('language', 'js');
      

      其中“语言”是键,“js”是您要存储的值。

      在您的情况下,您可以将数据转换为 JSON,将其放入 localStorage 并在页面刷新后检查您的密钥上的 localStorage 是否为空,然后将其从 JSON 转换回对象

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-09
        • 1970-01-01
        • 2019-01-17
        • 2012-05-27
        • 1970-01-01
        • 2019-04-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多