Search code examples
jqueryjsonhtmloffline-caching

Database for HTML5 offline application


How to use a JSON string(pretty large) as a database for HTML5

I know we can use localStorage.setItem('key',value) for storing a specific value.Im having a JSON string that contains 200 to 300 records

[{"key":"value"....},
{"key":"value"....},
{"key":"value"....},
......
.....
...
//around 300
]

Right now im putting this entire JSON in a div with display said to none and accessing that JSON like this

$.parseJSON($('#mydivid').html());

Any other alternate suggestion ? Thank you


Solution

  • I'm not sure I understand the problem.

    Supposing you have a json file (many MB if you like) generated by your server, you can fetch it with a simple ajax query, parse it, and then use it as

    var myval = database['somekey'];
    

    You shouldn't wrap it in your html, it prevents the normal caching of your page if only the database changes.

    Your json would be stored or generated in a second separate .json file (that you can very well generate in PHP).

    The function to fetch it would look like this :

    var database;
    
    function fetchDatabse(callback) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === 4) {
                if (httpRequest.status === 200) {
                    database = eval('('+httpRequest.responseText+')');
                    if (callback) callback();
                }
            }
        };
        httpRequest.open('GET', 'database.json?time='+(new Date().getTime()));
        httpRequest.send(); 
    }
    

    Note that it's usually better to fetch only parts of a database using ajax queries.


    If you really want to embbed your json in your page, instead of embedding it in a hidden div, embedd it in a script :

    <script>
    var database = {
       ...
    };
    </script>