LocalStorage和JSON.stringify JSON.parse

时间:2014-05-19 01:41:37

标签: javascript jquery json html5

我一直致力于一个项目,该项目允许用户提交有关他们访问过的地点的记忆,并跟踪记录提交时间的位置。我唯一的问题是尝试在应用程序中使用localStorage,我读到了JSON.stringify和JSON.parse,并且还不了解如何在我的代码中使用它们。

这是我的form.js 它处理表单并获取文本字段。当单击添加按钮(在显示详细信息页面上)或输入详细信息按钮时,它会清除表单。最后,它接收信息并将消息发送回窗口。

function processForm(){

var locate = document.myform.locate.value;
var details = document.myform.details.value;
var storeData = []; 
localStorage.setItem("locate", JSON.stringify(locate));
localStorage.setItem("details", JSON.stringify(details));
alert("Saved: " + localStorage.getItem("locate") + ", and " + localStorage.getItem("details"));

var date = new Date,
    day = date.getDate(),
    month = date.getMonth() + 1,
    year = date.getFullYear(),
    hour = date.getHours(),
    minute = date.getMinutes(),
    ampm = hour > 12 ? "PM" : "AM";    
    hour = hour % 12;
    hour = hour ? hour : 12; // zero = 12
    minute = minute > 9 ? minute : "0" + minute;
    hour = hour > 9 ? hour : "0" + hour;

    date = month + "/" + day + "/" + year + " " + hour + ":" + minute +  " " + ampm;

localStorage.setItem("date", JSON.stringify(date));

storeData.push(locate, details, date);
localStorage.setItem("storeData", JSON.stringify(storeData));   
}

function clearForm(){
$('#myform').get(0).reset();
}

function retrieveFormInfo(){

var data = JSON.parse(localStorage.getItem("storeData"));   

var locate = JSON.parse(localStorage.getItem("locate"));
$("#locate2").html("Place: " + locate);

var details = JSON.parse(localStorage.getItem("details"));
$("#details2").html("Description: " + details);

var date = JSON.parse(localStorage.getItem("date"));
$("#date").html(date);

}

但我遇到的主要问题是我确实知道如何使用JSON.stringify和JSON.parse正确地获取该信息,并将其动态地附加到带有html元素的窗口,主要就像一个记忆列表。 / p>

任何帮助表示赞赏!

4 个答案:

答案 0 :(得分:13)

localStorage仅存储键值对。

让我们假设你有一个数组存储,每个项目都是一个json对象。

你有两个选择:

选项1:

  • 将每个项目字符串化并存储在locaStorage中
var item = {input1: 'input1value', input2: 'input2value' };
localStorage.setItem( itemIndex, JSON.stringify(item) );
  • 检索项目迭代localStorage项目,然后将项目转换为JSON对象:
for(var i=0;i<localStorage.length; i++) {
  var key = localStorage.key( i );
  var item = JSON.parse( localStorage.getItem( key ) );
}

选项2:

  • 将整个数组字符串化并存储在localStorage

    localStorage.setItem( 'memoriesdata', JSON.stringify( arr ) );

  • 读取数据作为字符串读取项目然后转换为JSON对象

    var arr = JSON.parse( localStorage.getItem('memoriesdata') );

答案 1 :(得分:3)

首先将输入字段的值输入到javascript对象中。

var myMemory = {};
myMemory.location = document.getElementById('location').value;
myMemory.description = document.getElementById('description').value;

现在将myMemory保存到localStorage,这可以在表单提交或按下按钮时完成。我们可以存储为一系列记忆并每次都添加项目。

//if user already has memories in local, get that array and push into it.
//else create a blank array and add the memory.
memories = localStorage.getItem('memories') ?
              JSON.parse(localStorage.getItem('memories')) : 
              [];
memories.push(myMemory);
localStorage.setItem('memories', JSON.stringify(memories));

答案 2 :(得分:2)

我使用此Storage实现。它受到许多存储插件的启发......它处理JSON.stringify函数可以处理的任何值,并且应该工作xbrowser(以及'cookie-disabled'firefox):

//
//    api:
//
// .clear()    empties storage
// .each()     loops storage (key, value) pairs
// .fetch()    get a value by key
// .has()      checks if there is a key set
// .ls()       lists all keys 
// .raw()      string value actually stored
// .reload()   reads in serialized data
// .rm()       removes key(s)
// .set()      setup value(s)
// .type()     storage type used 'localStorage/globalStorage/userData'
// .valid()    is storage engine setup correctly
//
;
((function(name, def, glob, doc) {

  // add 'store' id to globals
  this[name] = def(glob, doc);
}).call(
  this, "store", function(glob, doc) {

    // private (function) store version
    var stclient;

    var driver = {
      // obj  : storage_native{},
      // type : storage_type
    };

    var engine = {
      // read  : (func),
      // write : (func)
    };

    var _ = {

      a: Array.prototype,
      del: function(node) { // , ...fields

        _.slc(arguments, 1).
        forEach(function(field) {
          delete this[field];
        }, node);

        return node;
      },
      each: function(array, callback, context) {

        context ||
          (context = array);

        array.
        some(function() {
          return false === callback.apply(context, arguments);
        });

        return array;
      },
      hasown: Function.prototype.call.bind(Object.prototype.hasOwnProperty),
      jsdc: JSON.parse, // decode
      jsec: JSON.stringify, // encode 
      keys: Object.keys, // shimed .keys
      ns: "storage5", // single property name to keep serialized storage data under
      object: null, // parsed storage data 
      slc: Function.prototype.call.bind(Array.prototype.slice),
      test: {

        isemptyobj: function(node) {
          for (var x in node)
            return false;
          return true;
        },

        isplainobj: function(node) {
          return '[object Object]' == Object.prototype.toString.call(node);
        },

      },
      testval: 'storage' + Math.random(), // test value for implementation check
      rig: function(target, items) {

        for (var field in items)
          if (items.hasOwnProperty(field))
            target[field] = items[field];

        return target;
      },
      clone: function(node) {
        return _.jsdc(_.jsec(node));
      },
      puts: function() {
        engine.write(_.jsec(_.object));
      },
    };

    stclient = function storage5() {
      return arguments.length ?
        storage5.set.apply(storage5, arguments) :
        storage5.fetch();
    };

    // _init on load|ready
    window.addEventListener('load', _init, false);

    return _.rig(stclient, {

      clear: function() {
        return _.object = {}, _.puts(), this;
      },

      each: function(callback, context) {

        context ||
          (context = this.fetch());

        _.each(this.ls(), function(field) {
          return callback.call(context, field, this.fetch(field));
        }, this);

        return this;
      },

      fetch: function(key) {
        return (arguments.length) ?
          _.object[key] : _.clone(_.object);
      },

      has: function(name) {
        return _.hasown(_.object, name);
      },

      ls: function() {
        return _.keys(_.object);
      },

      raw: function() {
        return engine.read();
      },

      reload: _load,

      rm: function() {

        _.del.apply(null, _.a.concat.apply([_.object], arguments));

        return _.puts(), this;
      },

      set: function(input, value) {

        var len = arguments.length;
        var flag = 1;

        if (len) {

          if (_.test.isplainobj(input)) {

            _.keys(input).
            forEach(function(field) {
              _.object[field] = input[field];
            });

          } else {

            if (1 < len)
              _.object[input] = value;
            else
              flag = 0;

          }

          flag && _.puts();

        }

        return this;
      },

      type: function() {
        return driver.type || null;
      },

      valid: function() {
        return !_.test.isemptyobj(driver);
      },

    });

    function _init() {

      var flag = 0;
      var stnative;

      if ("localStorage" in glob) {
        try {
          if ((stnative = glob["localStorage"])) {
            // inits localStorage 
            _initlocst(stnative, driver, engine);
            flag = 1;
          }
        } catch (e) {}
      }

      if (!flag) {

        if ("globalStorage" in glob) {
          try {
            if ((stnative = glob["globalStorage"])) {
              // inits globalStorage
              _initglobst(stnative, driver, engine);
              flag = 1;
            }
          } catch (e) {}
        }

        if (!flag) {
          // inits userDataStorage
          _initusrdatast(doc.createElement(_.ns), driver, engine);
        }
      }

      // parse serialized storage data
      _load();
    }

    function _initlocst(stnative, driver, engine) {

      stnative[_.testval] = _.testval;

      if (_.testval === stnative[_.testval]) {

        try {
          stnative.removeItem(_.testval);
        } catch (e) {
          try {
            delete stnative[_.testval];
          } catch (e) {}
        }

        driver.obj = stnative;
        driver.type = "localStorage";

        engine.read = function() {
          return driver.obj[_.ns];
        };

        engine.write = function(stringvalue) {
          driver.obj[_.ns] = stringvalue;
          return stringvalue;
        };

      }
    }

    function _initglobst(stnative, driver, engine) {

      var host = glob.location.hostname;

      driver.obj = (/localhost/i).test(host) ?
        stnative["localhost.localdomain"] : stnative[host];

      driver.type = "globalStorage";

      engine.read = function() {
        return driver.obj[_.ns];
      };

      engine.write = function(stringvalue) {
        driver.obj[_.ns] = stringvalue;
        return stringvalue;
      };

    }

    function _initusrdatast(node, driver, engine) {

      try {

        node.id = _.ns;
        node.style.display = "none";
        node.style.behavior = "url('#default#userData')";

        doc.
        getElementsByTagName("head")[0].
        appendChild(node);

        node.load(_.ns);

        node.setAttribute(_.testval, _.testval);
        node.save(_.ns);

        if (_.testval === node.getAttribute(_.testval)) {

          try {

            node.removeAttribute(_.testval);
            node.save(_.ns);

          } catch (e) {}

          driver.obj = node;
          driver.type = "userData";

          engine.read = function() {
            return driver.obj.getAttribute(_.ns);
          };

          engine.write = function(stringvalue) {
            driver.obj.setAttribute(_.ns, stringvalue);
            driver.obj.save(_.ns);
            return stringvalue;
          };

        }

      } catch (e) {
        doc.
        getElementsByTagName("head")[0].
        removeChild(node);
      }

      node = null;
    }

    function _load() {

      try {
        _.object = _.jsdc((engine.read() || engine.write("{}")));
      } catch (e) {
        _.object = {};
      }
    }

  }, window, document));

  //eof

答案 3 :(得分:2)

  

Vanilla JS

var printStorageBody = function () {
    var body = document.querySelector("body");
    var pre = document.createElement("pre");
    body.innerHTML = "";
    pre.innerText = JSON.stringify(localStorage, null, '\t');
    body.appendChild(pre);
}
  

的jQuery

var printStorageBody = function () {
    $("body").html("");
    $("<pre>")
    .text(JSON.stringify(localStorage, null, '\t'))
    .appendTo("body");
}