Saturday, October 5, 2013

How to store an array in localStorage

This tutorial assumes that you are already familiar with HTML5  localStorage.

Although HTML5  localStorage is very useful, its usage is restricted to key value mechanism. Key and value is stored in string format despite what we need. For an instance, though you can specify a boolean type (either true or false) as the value, it is stored as a string.

What if we need to store multiple items as the value for a certain key. This can be little bit tricky if you gonna place an array directly as the value. When we scratch the surface of localStorage basic principles this is not possible. However you can come up with your own solutions that might work for you.

This tutorial demonstrates a simple way of handling above problem using json. We gonna store array as a json string. So nothing new here.

First add jQuery library as we are using some jQuery functions.

[sourcecode language="javascript"]
<script type="text/javascript">
var favorites_str = localStorage.getItem('my_favorites');
if(favorites_str == null) {
favorites = [];
favorites.push({ "name":"keshi", "id":"6" });
} else{
favorites = JSON.parse(favorites_str);
favorites.push({ "name":"sara", "id":"6" });

}
localStorage.setItem('my_favorites',JSON.stringify(favorites));
</script>

[/sourcecode]

To verify that above script is functioning please copy and run below script. It will make things easy, if you put this code in  a separate file.

[sourcecode language="javascript"]
<script type="text/javascript">
var data = localStorage.getItem('my_favorites');
if(data == null){
alert("0 favorites");
}else{
favorites = JSON.parse(data);
$.each(favorites, function(index,item){
alert(item.name);

});
}
</script>

[/sourcecode]

No comments:

Post a Comment

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...