简体   繁体   中英

How do I save the inputs of an HTML form into a JSON file with JavaScript?

As my question already reveals, I am trying to save inputs from an HTML form to a json file - However I only get to save the inputs to the localStorage.

let movies = [];
        const addMovie = (ev)=>{
            ev.preventDefault();
            let movie = {
                id: Date.now(),
                title: document.getElementById('title').value,
                year: document.getElementById('yr').value
            }
            movies.push(movie);
            document.querySelector('form').reset();

            //saving to localStorage
            localStorage.setItem('key', JSON.stringify(movies) );
        }
        document.addEventListener('DOMContentLoaded', ()=>{
            document.getElementById('btn').addEventListener('click', addMovie);
        });

Now, I've already tried the fs.writeFile methods but somehow my pc doesn't want to import fs. So I'm asking if there's another way to write the inputs into JSON or how to fix the import fs bug.

In a web browser, you can invoke download in multiple ways. One of possibilities are window.open ing a window, redirection, or creating a link and invoking its click method.

 const jsonToDownload = '{"foo":42}' function download() { const aElem = document.createElement("A") aElem.href = 'data:application/octet-stream,' + jsonToDownload aElem.download = 'filename.json' aElem.click() }
 <button onclick=download()>Download</button>

You can use any filename. Just set the download attribute on the link to the filename.

If you want do download binary or large data, using BLOB object might be better idea. It is quite simple – create the BLOB, generate its URL, initiate the download and revoke the URL of the BLOB.

 const jsonToDownload = '{"foo":42}' function download() { const blob = new Blob([jsonToDownload, ], { type: 'application/json', }) const url = URL.createObjectURL(blob) const aElem = document.createElement("A") aElem.href = 'data:application/octet-stream,' + jsonToDownload aElem.download = 'a' aElem.click() URL.revokeObjectURL(url) }
 <button onclick=download()>Download</button>

Please note that the snippet above will not probably work, because StackOverflow's iframe usage prohibits this behavior in some browsers. Copy the code in your own HTML file adn try it there.

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