Use localStorage to hold ajax response and then use as object

14,842

You can only store strings in the localStorage, however you could create an abstraction of the serialization/deserialization process in a reusable function.

Have a look at Storing Objects in HTML5 localStorage

Also, it's recommended to use the setItem and getItem methods.

Share:
14,842
Rob
Author by

Rob

Updated on June 04, 2022

Comments

  • Rob
    Rob almost 2 years

    Hi have the following Ajax request that gets JSON from the server and stores the json in localStorage for which I can use in my application. It seems like my code to accomplish this is not efficient at all, but I cant get it to work any other way. I have tried storing as an object, but it seems to want to be stored as a string.

    Is there a better way to do this?

    //GET Users List from Server
    function getUsersList() {
        $.ajax({
            url: "api/ListUsers",
            dataType: "json",
            success: function (e) {
    
                localStorage.UsersList = (JSON.stringify(e));
                var usersList = localStorage.UsersList;
                var usersList = $.parseJSON(usersList)
                console.log(usersList[0])
            }
        });
    }