我想在localStorage中恢复变量而不替换现有变量?

时间:2016-05-17 09:20:05

标签: javascript jquery ajax

如何在本地存储中恢复价值请帮帮我.. ??

var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if( xhttp.readyState == 4 && xhttp.status == 200 )
        {
            var data = JSON.parse(xhttp.responseText);
            if ( data.hasOwnProperty(username.value) && data[username.value]["pass"] === password.value){

                saveLocalstorage('task' , JSON.stringify(data[username.value]["task"]));
                if(window.localStorage){
                    location.pathname += "redirect_page.html";
                    //console.log(JSON.stringify(localStorage));

                }else {
                    localStorage.clear();
                }
            }
            else {
                alert("user not available");
            }
        }
    }
    xhttp.open('GET',"user.json",true);
    xhttp.send()

我希望恢复"任务"变量

2 个答案:

答案 0 :(得分:1)

使用localStorage.setItem

localStorage.setItem('task' , JSON.stringify(data[username.value]["task"]))

答案 1 :(得分:1)

另一种保存在localStorage而不是localStorage.setItem()的方法是

localStorage.task = JSON.stringify(data[username.value]["task"]);

您可以将数据检索为

localStorage.task;