From what i understand, i'll have to save the array as a JSON file and then save that locally using HTML5 local storage. Does anyone have any examples so i can get my head around it. The tutorial showing up from Google don't seem very clear.
It can be quite straight-forward. Just put a delegate between your code and localStorage that converts all values from and to JSON:
// conversion functions
var fromJSON = JSON.parse,
toJSON = JSON.stringify;
// storage functions
var get = function(key) {
return fromJSON(localStorage[key]);
};
var set = function(key, value) {
localStorage[key] = toJSON(value);
};
Try CarboStorage. It handles objects automatically, including dates. Filtering is also supported.
http://carbogrid.com/index.php/storage/home
Related
How to write localStorage script which will remember the value of turning odometer...so that each time the user visits the site again , the odometer will resume on the value on which odometer was at when the user left the site? I'm beginner in javascript so please understand...
This is my code: https://jsfiddle.net/aht87opr/17/
I've found the following code which might help with my case: http://jsfiddle.net/Jonathan_Ironman/Hn7jc/
$('button').click(function() {
var mefedron = myOdometer.get();
$('#value').text(mefedron);
});
Nicely done on the odometer, looks good. Local storage is simple.
To set local storage:
localStorage.setItem("key", "value");
To get local storage:
var number = localStorage.getItem("key");
Be sure to try getting the local storage first so you can handle any null errors.
Get and Set
localStorage has a few ways to get and set values to the browser. The simplest is treating it like a regular object.
localStorage.distance = 55;
you can then retrieve the value by accessing the property name you created earlier.
console.log(localStorage.distance); // "55"
Strings are stored, parse the string
Notice that localStorage.distance was set as a number but when accessed was a string. If you only need to store a number you could pass the string through a function like parseInt().
console.log(parseInt(localStorage.distance)); // 55
Another solution is to use JSON
create an object model of your odometer.
var odometer = { distance: 55, timeForOilChange: false };
Then write to the localStorage passing your model through JSON.stringify
localStorage.odometer = JSON.stringify(odometer);
and read the value back out using JSON.parse
console.log(JSON.parse(localStorage.odometer));
// { distance: 55, timeForOilChange: false }
I have a set of data in a JSON file that consists of UserIDs (as keys) and Passwords (values). I want to read the same using JavaScript for validation purposes. My JSON is :
IDsNPass = '[{"A":"A15"},{"B":"B15"},{"C":"C15"}]';
I have an idea about how to access the data using JavaScript as long as the keys in the JSON remain the same. But here, the keys in my JSON are not constant all along.
Any help on how to get along with the JavaScript is much appreciated!
First of all, your design is not a good format.
If you only have a id-password mapping in on object, you can do like this
var ip = JSON.parse(IDsNPass)
for(var obj in ip) {
for(var key in obj) {
console.info(key)
console.info(obj[key])
}
}
I'm new to jQuery and just playing for fun. I have some code that I want to try to modify for my needs but the current js file is getting its data from google spreadsheets and then returning each item as objects. I don't use json to pass data from my server to jQuery so I'm wondering how I can convert json to objects.
The current way its doing it is(tabletop is the name of their js program that gets data from google docs):
Tabletop.init({
key: timelineConfig.key,
callback: setupTimeline,
wanted: [timelineConfig.sheetName],
postProcess: function(el){
//alert(el['photourl']);
el['timestamp'] = Date.parse(el['date']);
el['display_date'] = el['displaydate'];
el['read_more_url'] = el['readmoreurl'];
el['photo_url'] = el['photourl'];
}
});
I have added alerts all over the file and I think this is the area that gets the data and passes it on. I was thinking of trying to replace items in their object with objects from my json and see if it changes anything, but I'm unsure. Typrically I pass individual items via json,hashmaps, and lists, not sure how it works with objects or how to access objects(I simply call url's that I create for the requests, $("#user-history").load("/cooltimeline/{{ user.id }}");). But where do I start if I want to turn json data into objects?
If it helps, here's the demo of what I'm trying to do(but by having it use json data).
p.s. I'm really looking for the logic of how to complete what I'm trying to do and perhaps some ideas I'm missing so I can google them and learn.
Use use function JSON.parse(json) :) Or jQuery.parseJSON(json)
var json = '{"a":2}';
var object = JSON.parse(json);
alert(object.a);
You should see alert with message: 2
I don't realy know if I understand your comment, but maybe you want just do this:
postProcess: function(el){ //here el is JSON string
el = JSON.parse(el); // now el is an object
el.timestamp = Date.parse(el.date);
el.display_date = el.displaydate;
el.read_more_url = el.readmoreurl;
el.photo_url = el.photourl;
return el;
}
Btw. you do not need to use brackets on know property names without not standard names:
el['timestamp'] === el.timestamp
It will be easier if you paste your JSON
Hmmm.. I have this json values:
var form = {
lat: event.row['lat'].value,
lon: event.row['lon'].value,
}
Android.openForm( $.toJSON(form) );
How do I get the value from lat and long?
openForm: function( json ){
alert(json[lat]);
//$('#lat').val(json.lat);
}
If the results of form is to be this
var form = {
lat: "somevalue",
lon: "somevalue"
};
You would access the data in the variable form by the dot properties.
form.lat and form.lon
Simple Fiddler
Why don't you have the openForm receive the object directly instead of its json serialization?
openForm(form){
var json = $.toJSON(form);
alert(form.lat);
}
$.toJSON(form) converts your object to a string, I think you want to pass the object so just drop it:
Android.openForm(form);
Didn't realize that my team mate was using a plugin...
http://code.google.com/p/jquery-json/
I should have asked him first.. #_#
Sorry neh
var thing = {plugin: 'jquery-json', version: 2.3};
var encoded = $.toJSON( thing );
// '{"plugin":"jquery-json","version":2.3}'
var name = $.evalJSON( encoded ).plugin;
// "jquery-json"
var version = $.evalJSON(encoded).version;
// 2.3
Try this
openForm: function( json ){
var lat = json.lat;//or json["lat"]
var lon = json.lon;//or json["lon"]
}
By the way variable form is already a well formed json you don't have to convert it to json in order to use it.
If $.toJSON is a method like JSON.stringify, then you've serialized the data into JSON text, so it's values are no longer available via properties.
You'd need to parse it first.
openForm: function( json ){
// UPDATED to use the JSON plugin you've loaded
var parsed = $.evalJSON( json );
alert( parsed[lat] );
}
I assume that the original form variable is not accessible from where you're trying to retrieve the value, otherwise you probably wouldn't serialize it in the first place.
If the original form data is in the same execution environment, and could be accessed directly from your function, you should do that instead of serializing.
What is JSON, and why do we use it?
For those who don't understand what JSON is meant for, it is a text based serialization format used to transfer data between environments where data can not naturally be shared.
The serialization is simply a standardized format that gets "stringified" from the native data structures of one environment, and then parsed into the native data structures of a different environment.
I assume toJSON is the "stringify" function, and the openForm is the separate environment into which the JSON data has been transferred.
If these assumptions are correct, the JSON needs to be parsed into the new environment before its values can be easily accessed.
Is it possible that the same name used can have many different values stored separately and to be shown in a list?
E.g.:
function save()
{
var inputfield = document.getElementById('field').innerHTML;
localStorage['justified'] = inputfield;
}
<input type="text" id="field" onclick="save();" />
Every time someone enters something in the input field, and click on save, the localstorage will only save the value in the same name, however, does this conflict the way storage are saved, like being replaced with the latest input value?
Also, is there any way to prevent clearing the localstorage when clearing the cache?
Actually localStorage 'should' be capable of storing integers, strings and arrays. I have been working on a notepad app using localStorage and save all my data using object literals:
var someData = {
withvars: "and values",
init: function() {
// not sure if this works but it should.
},
var1: {
subvar1: "data",
subvar2: "data2"
}
};
Then store it using JSON.stringify():
localStorage.setItem(varName, JSON.stringify(someData));
Then access it later with JSON.parse():
var dataBack = JSON.parse(localStorage.getItem("varName"));
If you always use object literals then you will have less trouble keeping track of how to store and how to retrieve data from localStorage.
No. You can store only one value in a localStorage entry.
There are two ways to store more values behind one keyword:
Use localStorage['justified_0'], localStorage['justified_1'] etcetera.
Store multiple values in an array and convert it to JSON before storing in localStorage['justified'] and convert it back to an array after reading.
Clearing the cache does not clear local storage.
This is something quite easily determined with a very simple test page. You can only store one value per key, and the values are not cleared when the cache is cleared. (I've just tried Firefox so far ...)
You can store a list of values in a single key by writing your own function to do it:
function addToPersistentList(listName, value) {
var val = localStorage[listName] || [];
val.push(value);
localStorage[listName] = val; // THIS DOES NOT WORK
}
edit oops it only supports stored strings; crap. OK well if you have json2 you'd do this:
function addToPersistentList(listName, value) {
var val = localStorage[listName] ? JSON.parse(localStorage[listName]) : [];
val.push(value.toString());
localStorage[listName] = JSON.stringify(val);
}
Of course this causes issues if you want to store dates etc.