Best way to save javascript data in localstorage

假如想象 提交于 2021-02-05 08:34:36

问题


I want to be able to create JavaScript note objects and dynamically delete them using a navbar pane.

var sel = window.getSelection();
var range = sel.getRangeAt(0);
var editor = { "startContainer": range.startContainer, "startOffset": range.startOffset, "endContainer": range.endContainer, "endOffset": range.endOffset };

Then using a message I would pass the location and message into a function to add notes:

Notes(editor, message);
function Notes(location, note) {
  this.location = location;
  this.note = note;
}

I'm trying to wrap my brain around how to actually save the data locally.

function addNote() {
  // if(tyepof(Storage) !== "undefined"){
  //   if(localStorage.notes){
  //     localStorage.notes
  //   } else {
  //     localStorage.notes = 
  //   }

  localStorage.setItem()
}

Is localStorage the way to go? I know sessionStorage only stores for a session.


回答1:


Here's a quick way to generate a few elements from a localStorage.getItem() call and could maybe also help you out here along with Nelson's answer. Click on the button in the fiddle and you'll see the code grab the localStorage objects and use them to create some simple <li>'s.

Fiddle: http://jsfiddle.net/kfrvdnux/

Example code:

HTML

<button id='save'>Click the save button...</button>
<div id='content'></div>

JS

var content = document.getElementById('content'),
    save    = document.getElementById('save'),
    output  = '<ul>',
    animals = [{
      name: 'bob',
      type: 'dog'
    }, {
      name: 'fred',
      type: 'lizard'
    }];

// set on load for testing
localStorage.setItem('animals', JSON.stringify(animals));

// grab localStorage data on click and create a list
save.addEventListener('click', function() {
    var ls = JSON.parse(localStorage.getItem('animals'));  
    for (var i = 0; i < ls.length; i++) {
      output += '<li>' + ls[i].name + ', ' + ls[i].type + '</li>';
    }

  output += '</ul>';
  content.innerHTML = output;
});



回答2:


You have many ways of doing this. In fact so many that is not praticable to explain all of them. It depends on you actual intent. If you just want notes you can loose aftwards, localStorage may be the way to go.

But for most applications you typically would do this sending data to a server that would be responsible for storing the data. In the server the data could be stored in a database, in local files, there are many ways. Servers could be Node.js (if you want to stick to js only), or any other language that has server capabilities. That would be pratically all. Most used are Node, PHP, Python, Java and others. You would prepare a certain url to receive a post with the data that needs to be saved and then make the client send an ajax request to this url with it. in this question you can get some examples of how to start doing this:

Basic Ajax send/receive with node.js

the server save part is up to you :)

edit

here is a small tutorial about localStorage

https://www.taniarascia.com/how-to-use-local-storage-with-javascript/

just remember that every time you reload the page you will loose everything. In order to save the data you have to send it to a server.

Another thing: you don't need to buy a dedicated server to do this. You can implement the server in your own machine. This is a relatively easy task. Not that complicated. I advise you to take a look in the SO question above about basic ajax send/receive, before you rule this out.




回答3:


Are you trying to save .txt files locally to the computer? I don't believe JavaScript has this function because it would be a huge security hole. My understanding is that you could create cookie files on the local machine but that is about it.

If you need to export files you could always use an ASP.NET/PHP to create files on a server, then the user could click on a link that would prompt you to save the dynamically created file.

Based on the comment below you should create an array of objects.

var array = [];
array[array.length] = {name: 'NAME CONTENT', other: 'Other content', number: 1}
array[array.length] = {name: 'NAME CONTENT 2', other: 'Other content 2', number: 1}

You can then get a function to do things with your object by doing something like this

PrintInfo(array[i]);

function PrintInfo(aSingleObject){
    console.log(aSingleObject.name);
    console.log(aSingleObject.other);
    console.log(aSingleObject.number);
}

To remove objects from your array using the splice command

var array = [2, 5, 9];
console.log(array)
var index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}
// array = [2, 9]
console.log(array);


来源:https://stackoverflow.com/questions/51992769/best-way-to-save-javascript-data-in-localstorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!