如何在会话存储中设置/获取/保存数据?

时间:2018-05-04 17:19:05

标签: javascript jquery local-storage session-storage sessionstorage

这里是我在ajax调用响应成功后获得的数据示例obj.DATA如下所示:

{
  "A43D": {
    "FIRSTNAME": "Mike",
    "EMAIL": "mjohns@gmail.com",
    "LASTNAME": "Johns"
  },
  "4E83": {
    "FIRSTNAME": "Steve",
    "EMAIL": "scook@gmail.com",
    "LASTNAME": "Cook"
  }
}

$.ajax({
   type: 'POST',
   url: 'AjaxFunctions.cfc?method=getCustomers',
   data: formData,
   dataType: 'json'
}).done(function(obj){
   console.log(obj.DATA);
   sessionStorage.setItem("customersData", JSON.stringify(obj.DATA));      
}).fail(function(jqXHR, textStatus, errorThrown){
   alert('Error: '+errorThrown);
}); 

然后我将sessionStorage转储到console.log(sessionStorage),我看到了:

{
  "customersData": "{\"A43D\":{\"FIRSTNAME\":\"Mike\",\"EMAIL\":\"mjohnes@gmail.com\",\"LASTNAME\":\"Johnes\"},\"4E83\":{\"FIRSTNAME\":\"Steve\",\"EMAIL\":\"scook@gmail.com\",\"LASTNAME\":\"Cook\"}}"
}

所以我接下来尝试了:

sessionData = sessionStorage.hasOwnProperty(customersData[recordID]) ? JSON.parse(sessionStorage.getItem(customersData[recordID])) : null;

这是我只传递记录ID然后尝试在会话存储中访问该记录的函数。如果我尝试console.log(sessionData),我看到的只是null。我想知道如何访问会话存储中的customersData对象中的特定键?我如何在sessionStorage customersData对象中插入/编辑记录?

2 个答案:

答案 0 :(得分:2)

每次尝试为localStorage / sessionStorage保存/加载某些内容并且您知道它是一个json对象时,请始终根据具体情况进行字符串化/解析。

这里你已经修好了你的代码。

注意:我尝试创建一个代码段,但由于我们无法访问沙箱的sessionStorage,因此无效。

注意2:始终检查要解析的数据,如果存储上没有该记录,则会返回Goal : 2 i = 0: 0, 0 i = 1: 0, 0 i = 2: 0, 0 i = 3: 0, 0 i = 4: 0, 0 i = 5: 0, 0 i = 6: 0, 0 Test 19244512, 0

null

答案 1 :(得分:1)

这是我如何处理这个问题,
通过使用方法创建一些customersStorage对象,例如getsetadd

<强> jsFiddle demo

var customersStorage = {
    // Get all or single customer by passing an ID
    get: function( id ) {
        var parsed = JSON.parse(sessionStorage.customersData || "{}");
        return id ? parsed[id] : parsed;
    },
    // Set all
    set: function( obj ) {
        return sessionStorage.customersData = JSON.stringify(obj || {});
    },
    // Add single customer and store
    add: function( id, obj ) {
        var all = this.get();
        // Make sure customer does not exists already;
        if(all.hasOwnProperty(id)) return console.warn(id+ " exists!");
        all[id] = obj;
        return this.set(all);
    }
};

// Let's play!

// Store All
customersStorage.set({
  "A43D": {
    "FIRSTNAME": "Mike",
    "EMAIL": "mjohns@gmail.com",
    "LASTNAME": "Johns"
  },
  "4E83": {
    "FIRSTNAME": "Steve",
    "EMAIL": "scook@gmail.com",
    "LASTNAME": "Cook"
  }
});

// Get single
console.log( customersStorage.get("4E83") );

// Add new 
customersStorage.add("AAA0", {
  "FIRSTNAME": "Espresso",
  "LASTNAME": "Coffee",
  "EMAIL": "espresso@coffee.com"
});

// Get all
console.log( customersStorage.get() );

此外,要使会话处理对象更多“client”不可知,我会扩展它以通过 namespace 处理更多数据:

var ObjectStorage = function(nsp, useSession) {
  var stg = (useSession ? sessionStorage : localStorage);
  return {
    // Get all or single customer by passing an ID
    get: function(id) {
      var parsed = JSON.parse(stg[nsp] || "{}");
      return id ? parsed[id] : parsed;
    },
    // Set all
    set: function(obj) {
      return stg[nsp] = JSON.stringify(obj || {});
    },
    // Add one to all
    add: function(prop, val) {
      var all = this.get();
      // Make sure property does not exists already;
      if (all.hasOwnProperty(prop)) return console.warn(prop + " exists!");
      all[prop] = val;
      return this.set(all);
    }
  }
};

// Let's play!

// Create instance. Use true to use sessionStorage (instead of localStorage)
var Customers = new ObjectStorage("customersData", true);
// now you can use .add(), .get(), .set() on your Customers Object