Download a JSON text file in the webpage using only JavaScript/jQuery
I have a webpage that runs locally on my machine with just JavaScript and HTML5 localstorage (no need for a webserver). I already have the method for uploading a JSON/plain text file to the webpage using JavaScript only and converting it to a JavaScript object so my webpage can use it. Now I just need a way to export the object back to JSON text and then let the user save/backup the data using pure JavaScript/HTML only.
Ok so sample code thus far:
var obj = {
id: 24,
name: 'Jack Bauer'
};
var jsonText = JSON.stringify(obj);
Now assume there's a button saying Export/Backup, how do I let the user save that jsonText a开发者_StackOverflow中文版s a file on their hard drive using JavaScript/HTML only?
Many thanks!
Pretty sure you can't do that. The command document.execCommand('saveas', blah, blah) will save the current webpage (not the content you specify with javascript), and aside from that there is no way to get the save as dialog up from just javascript.
Some other options:
- use localstorage
- use a cookie
- display the jsontext in a textarea/prompt dialog/etc and ask the user to copy it and save it somewhere (yuck!)
- send the jsontext to (eg) a php server, add a content-disposition header to display a save as dialog.
I think it will work if you serve the file with application/octet-stream
as the content type. You'll need to configure your webserver to do so.
精彩评论