【问题标题】:localStorage is saved but cannot retain data on browser after web page reloadlocalStorage 已保存,但网页重新加载后无法在浏览器上保留数据
【发布时间】:2017-07-18 09:11:31
【问题描述】:

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

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

哈巴狗文件

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

js文件

$('#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

【问题讨论】:

  • messages有什么用= [];当您在 localStorage 中保存味精时
  • 您正在覆盖 localStorage 中的消息,并且您没有从 localStorage 中检索它
  • 这是一个实时聊天,如果我没弄错用户会提交消息,所以它需要遍历用户发送的所有消息并显示在客户端。
  • @ShubhamKhatri 你能指定哪个部分吗?
  • 你正在覆盖本地存储中的消息localStorage.setItem('message', msg);

标签: javascript jquery arrays html local-storage


【解决方案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);
}

【讨论】:

  • 感谢您的回答!
【解决方案2】:

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

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

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

所以在保存之前对数组进行字符串化。

当您检索它时,
您必须将其解析回一个数组,以便能够将新消息推送到其中。

好的...那么您会尝试同步 3 个或更多数组吗?

我建议使用一个对象数组。
每个对象都包含链接到特定消息的所有相关信息。

查看代码中的 cmets。

$('#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

【讨论】:

  • 感谢您的回答,它工作得很好,但是为什么重新加载后附加数据会丢失,因为它已经存储了 localStorage。
  • 因为页面已重新加载!但是您可以循环考虑加载时保存的消息以附加它们。
猜你喜欢
  • 1970-01-01
  • 2017-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多