admin管理员组

文章数量:1294297

here is example of my data that I get after ajax call response is successful obj.DATA looks like this:

{
  "A43D": {
    "FIRSTNAME": "Mike",
    "EMAIL": "[email protected]",
    "LASTNAME": "Johns"
  },
  "4E83": {
    "FIRSTNAME": "Steve",
    "EMAIL": "[email protected]",
    "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:

{
  "customersData": "{\"A43D\":{\"FIRSTNAME\":\"Mike\",\"EMAIL\":\"[email protected]\",\"LASTNAME\":\"Johnes\"},\"4E83\":{\"FIRSTNAME\":\"Steve\",\"EMAIL\":\"[email protected]\",\"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. If I try to console.log(sessionData) all I see is null. I'm wondering how I can access specific key in customersData object inside of the session storage? Also how I would insert/edit record in sessionStorage customersData object?

here is example of my data that I get after ajax call response is successful obj.DATA looks like this:

{
  "A43D": {
    "FIRSTNAME": "Mike",
    "EMAIL": "[email protected]",
    "LASTNAME": "Johns"
  },
  "4E83": {
    "FIRSTNAME": "Steve",
    "EMAIL": "[email protected]",
    "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:

{
  "customersData": "{\"A43D\":{\"FIRSTNAME\":\"Mike\",\"EMAIL\":\"[email protected]\",\"LASTNAME\":\"Johnes\"},\"4E83\":{\"FIRSTNAME\":\"Steve\",\"EMAIL\":\"[email protected]\",\"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. If I try to console.log(sessionData) all I see is null. I'm wondering how I can access specific key in customersData object inside of the session storage? Also how I would insert/edit record in sessionStorage customersData object?

Share Improve this question asked May 4, 2018 at 17:19 espresso_coffeeespresso_coffee 6,11012 gold badges94 silver badges220 bronze badges 2
  • 2 sessionStorage.getItem("customersData") will return you the JSON you stored there. You need to run it through JSON.parse() to get an object out again. – VLAZ Commented May 4, 2018 at 17:23
  • @vlaz How I would check for existence of the recordID in sessionStorage? Seems little over plicated... – espresso_coffee Commented May 4, 2018 at 17:31
Add a ment  | 

2 Answers 2

Reset to default 5

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.

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.

NOTE2: always check what data are you going to parse, if the record doesnt exist on the storage, it will return null.

var data = {
  "A43D": {
    "FIRSTNAME": "Mike",
    "EMAIL": "[email protected]",
    "LASTNAME": "Johns"
  },
  "4E83": {
    "FIRSTNAME": "Steve",
    "EMAIL": "[email protected]",
    "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

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": "[email protected]",
    "LASTNAME": "Johns"
  },
  "4E83": {
    "FIRSTNAME": "Steve",
    "EMAIL": "[email protected]",
    "LASTNAME": "Cook"
  }
});

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

// Add new 
customersStorage.add("AAA0", {
  "FIRSTNAME": "Espresso",
  "LASTNAME": "Coffee",
  "EMAIL": "[email protected]"
});

// 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

本文标签: javascriptHow to setgetsave data in session storageStack Overflow