javascript 使用 localStorage 保存 ajax 响应,然后用作对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16026167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:58:32  来源:igfitidea点击:

Use localStorage to hold ajax response and then use as object

javascriptjqueryajaxjsonlocal-storage

提问by Rob

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.

嗨,有以下 Ajax 请求,它从服务器获取 JSON 并将 json 存储在 localStorage 中,我可以在我的应用程序中使用它。似乎我的代码完成此操作根本没有效率,但我无法以任何其他方式使其工作。我试过存储为一个对象,但它似乎想存储为一个字符串。

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])
        }
    });
}

采纳答案by plalx

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

您只能在 中存储字符串localStorage,但是您可以在可重用函数中创建序列化/反序列化过程的抽象。

Have a look at Storing Objects in HTML5 localStorage

看看在 HTML5 localStorage存储对象

Also, it's recommended to use the setItemand getItemmethods.

此外,建议使用setItemgetItem方法。