简体   繁体   English

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

[英]How to set/get/save data in session storage?

here is example of my data that I get after ajax call response is successful obj.DATA looks like this: 这是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);
}); 

Then I dump sessionStorage in console.log(sessionStorage) and I see this: 然后我将sessionStorage转储到console.log(sessionStorage) ,我看到了:

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

So I was trying next: 所以我接下来尝试:

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

This is in the function where I just pass record id and then try to access that record in session storage. 在此函数中,我只是传递记录ID,然后尝试在会话存储中访问该记录。 If I try to console.log(sessionData) all I see is null . 如果我尝试console.log(sessionData)我看到的只是null I'm wondering how I can access specific key in customersData object inside of the session storage? 我想知道如何访问会话存储内部的customerData对象中的特定键? Also how I would insert/edit record in sessionStorage customersData object? 另外,我将如何在sessionStorage customerData对象中插入/编辑记录?

each time you try to save/load something for the localStorage/sessionStorage and you know it is a json object, always stringify/parse it depending on the case. 每次您尝试为localStorage / sessionStorage保存/加载某些内容时,您都知道它是一个json对象,请根据情况始终对其进行字符串化/解析。

here you have your code fixed to work. 在这里,您已将代码固定为可以工作的。

NOTE: I tried to create a snippet but it didn't work because we can not access to the sessionStorage of a sandbox. 注意:我尝试创建一个代码段,但由于无法访问沙箱的sessionStorage,因此无法正常工作。

NOTE2: always check what data are you going to parse, if the record doesnt exist on the storage, it will return null . 注意2:始终检查要解析的数据,如果存储中不存在该记录,它将返回null

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

//here we save the item in the sessionStorage.
sessionStorage.setItem("customersData", JSON.stringify(data));


//now we retrieve the object again, but in a string form.
var customersDataString = sessionStorage.getItem("customersData");
console.log(customersDataString);

//to get the object we have to parse it.
var customersData = JSON.parse(customersDataString);
console.log(customersData);

Here's how I'd approach this, 这是我的处理方法,
by creating some customersStorage Object with methods like get , set and add 通过使用诸如getsetadd类的方法创建一些customersStorage对象

jsFiddle demo jsFiddle演示

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() );

Furthermore, to make your session handling object more "client" agnostic I'd expand it to handle even more data by 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM