localStorage已保存,但在重新加载网页后无法在浏览器上保留数据

时间:2017-07-16 10:58:18

标签: javascript jquery arrays html5 local-storage

我正在尝试在localStorage(或sessionStorage)上保存聊天消息并在网页上显示,我可以找到存储在Devtool中的键值对 - >申请 - > localStorage,每当用户发送消息并在网页上显示时,消息值都会更新。但是每次页面重新加载时内容都会消失。怎么解决这个问题?

我遇到的是push()将消息保存到数组将替换而不是添加值,不确定这两个问题是否相关。感谢。

pug文件

#test2(style='height:200px; width:200px; border:1px solid #ccc')

js file

$('#sendMessage').on('click', function() {

        var msg = $('#message').val()
        var messages = [];
        console.log(typeof(messages)); //obj
        messages.push(msg);
        console.log(messages); //array value
        if (localStorage) {
            for (var i = 0; i < messages.length; i++) {
                localStorage.setItem('message', msg);
            }
            localStorage.setItem('username', $('#username').val());
            localStorage.setItem('date', currentTime());

            var cUser = localStorage.getItem('username');
            var cMsg = localStorage.getItem('message');
            var cTime = localStorage.getItem('date');

        } else {
            console.log('localStorage is not supported.');
        }

        document.getElementById("test2").innerHTML += "<div>" + cUser + " : " + cMsg + "</div>";
        // Clear the field
        $('#message').val('');
    }); // End click

重新加载页面丢失数据

    // Send Message
$('#sendMessage').on('click', function() {
    // get value
    var username = $('#username').val();
    var msg = $('#message').val();
    var time = currentTime();

    //check if localStorage works and create msgArray

    if (!localStorage) {

        console.log('localStorage is not supported.');

    } else {

        //check if there is existing message array in msgArray
        var msgArray = localStorage.getItem('message');
        //if there is NULL, setup msgArray = [], converts a JavaScript value to a JSON string
        if (JSON.stringify(msgArray) == 'null') {
            msgArray = [];
        } else {
            //else parses a JSON string, constructing the JavaScript value or object described by the string
            msgArray = JSON.parse(msgArray);
        }
    }

    //add new message object to msgArray

    var newMsg = {
        msg: msg,
        username: username,
        time: time
    };

    msgArray.push(newMsg);
    // stringsfy the message and store it to localStorage
    localStorage.setItem('message', JSON.stringify(msgArray));

    // dispaly current messages

    var cMsg = JSON.parse(localStorage.getItem('message'));
    // console.log(cMsg); // should shows list of array with new added message objects
    // for (var i = 0, max = cMsg.length; i < max; i++) {

    //document.getElementById("test2").innerHTML += "<div>" + cMsg[i].username + " : " + cMsg[i].msg + " at " + cMsg[i].time + " </div>";
    $('#test2').append('<div class="well well-sm">' + cMsg[cMsg.length - 1].username + ' : ' + cMsg[cMsg.length - 1].msg + ' <span class="pull-right"><small id="date"> at ' + cMsg[cMsg.length - 1].time + '</small></span></div>');

    // load the bottom of message
    var objDiv = document.getElementById("chatArea");
    objDiv.scrollTop = objDiv.scrollHeight;

    // Clear the field
    $('#message').val('');
}); // End click

2 个答案:

答案 0 :(得分:1)

我不确定你要用for循环完成什么,因为你似乎设置了与你有消息一样多次的相同值(基本上没有价值,设置一次应该足够了) )

让我们重新审视您的步骤:

您从输入元素中获取带有id消息的值,并将其保存到msg变量

var msg = $('#message').val()

您构建一个新数组,并将其推入

var messages = [];
messages.push(msg);

然后迭代数组,但重新使用msg变量

for (var i = 0; i < messages.length; i++) {
    localStorage.setItem('message', msg);
}

基本上,你这样做了:

localStorage.setItem('message', $('#message').val());

仅此而已。也许你想首先获得消息数组,然后将新消息添加到它,而不是像下面这样的

function addMessage() {
  // get the potential array
  var messages = JSON.parse( localStorage.getItem('message') || '[]' );
  // add the message
  messages.push($('#message').val());
  // save the array as a string, using JSON.stringify
  localStorage.setItem('message', JSON.stringify( messages));
  // empty the message value
  $('#message').val('');
  console.log(messages);
}

答案 1 :(得分:0)

如果您想保存一些聊天消息,我认为您应该确保所有消息都与作者的用户名和写入时间正确链接。

您尝试了一个数组...用于消息,但不用于其他信息。
你误用了数组。

LocalStorage只会存储一个字符串 嗯...我认为它也可以存储物品......但是我总是存储字符串是我的习惯 这样,它总是可以快速控制台记录,而不是窃听......

因此在保存之前对数组进行字符串化。

当你进行检索时,你必须将它解析回数组才能将新信息输入其中。

好的......那么你会尝试同步3个或更多阵列吗?

我建议使用一系列物体 每个对象包含链接到特定消息的所有相关信息。

请参阅代码中的注释。

$('#sendMessage').on('click', function() {

  // ...
  var chatWindow = $("#chatWindow");

  // Get all values now.
  var msg = $('#message').val();
  var username = $('#username').val();
  var time = moment().format("hh:mm:ss");


  if (!localStorage) {
    console.log('localStorage is not supported.');

  }else{
    // Retreive previous messages
    var messageArray = localStorage.getItem('message');


    // If there was none, set it as an array
    if(JSON.stringify(messageArray) == "null"){
      console.log(JSON.stringify(messageArray));
      messageArray = [];

      // If there was, get them back from string to an array of objects.
    }else{
      messageArray = JSON.parse(messageArray);
    }

    // Set the new message object.
    var newMsg = {msg:msg,
                  time:time,
                  username:username
                 }
    // Insert the new message object in the array.
    messageArray.push(newMsg);

    // Save the array as a string.
    var messagesStringified = JSON.stringify(messageArray);
    localStorage.setItem('message', messagesStringified);




    // I suppose that showing the messages from what is saved re-assures you about the saving...
    var cMsg = localStorage.getItem('message');

    // Empty chatWindow
    chatWindow.empty();

    // Loop through the messages.
    var allMessages = JSON.parse(cMsg);

    for(i=0;i<allMessages.length;i++){
      chatWindow.append("<div>" +
                        allMessages[i].time +
                        " | "+ allMessages[i].username +
                        " : " + allMessages[i].msg + "</div>");
    }
    console.log(JSON.stringify(messageArray));



    // Clear the field
    $('#message').val('');
  }
}); // End click


$('#clear').on('click', function() {
  localStorage.clear();
});

查看**CodePen