How do I save data on LocalStorage in Ruby on Rails 3.2.8?

后端 未结 4 941
走了就别回头了
走了就别回头了 2021-01-02 10:42

I\'m trying to save a variable called persistent_data.

I usually use session[:persistent_data] or cookies[:persistent_data], b

4条回答
  •  鱼传尺愫
    2021-01-02 11:09

    well this is quite simple and need to understand how local storage works.

    You can do that directly or (and this is probably cleaner) use the setItem() and getItem() method:

    localStorage.setItem('color','blue');
    

    If you read out the color key, you will get back “blue”:

    localStorage.getItem('color');`// output will be blue`
    

    To remove the item, you can use the removeItem() method:

    localStorage.removeItem('color');
    

    annoying thing is when you have an array, it will not be stored the right way.

    var car = {};
    car.wheels = 4;
    car.doors = 2;
    car.sound = 'vroom';
    car.name = 'Suzuki Mehran';
    console.log( car );
    localStorage.setItem( 'car', car );
    console.log( localStorage.getItem( 'car' ) ); //output as `[object Object]`
    

    but no need to worry we have a solution for that too.. You can work around this by using the native JSON.stringify() and JSON.parse() methods:

    localStorage.setItem( 'car', JSON.stringify(car) );
    

    and you can get it back by simply

    JSON.parse( localStorage.getItem( car ) );
    

    hope you have not any confusion now !!!

提交回复
热议问题