简体   繁体   中英

Create a text file using client side code

有没有一种方法可以仅使用客户端代码(不使用服务器端代码/ Web服务)来创建文本文件(并向其中写入一些JSON数据)?

您可以使用本地存储在客户端存储数据,但是无法在服务器端进行存储。

My best guess would be that you need to use javascript localstorage to store json.

example :

var myObject = {};
localstorage['myKey'] = myObject;
var secObject = localstorage['mykey'];

//you couls also use :
localstorage.setItem('myKey', myObject);
secObject = localstorge.getItem('myKey');

I usually "stringify" my JSON before saving it in case i need to modify "myObject" after saving it (because when you copy an object you actually copy a reference to it)

localstorage['myKey'] = JSON.stringify(myObject);
secObject = JSON.parse(localstorage['myKey']);

How are you all missing his point? You are able to generate text files and .csv files on client side and deliver it as a download.

var element = document.createElement('a');
 element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);
  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
}

// Start file download.
download("hello.txt","This is the content of my file :)");

From this link: https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM