简体   繁体   中英

I want to storage data from html forms. But I want to make it saved to a local file (a text or csv file - for categorization - )

I have a project which is for saving some films that i watched. Its a listing website. Part 1# (Entry Panel) I will have a panel which includes a form that i input the film's specifications(name,category,actors etc.). Then when i click the submit button it will save the data locally (in a csv or txt file). Of course i should be able to append new films to that file. Part 2# (viewer) And in the main page i need to see the films as lines in a HTML table. The table will be filled by the datas from the file i saved (Js loops will be needed i guess). If that topic is different than i ask, if there is another way, please manage me how to search. Im thinking that i must learn SQL for more complicated data storages. Here is the simple website:

   <!DOCTYPE html>
    <html>
    <head>
        <title>Film Lister</title>
    </head>
    <body>
    
    <form>
        <input type="text" name="movie-name">
        <input type="text" name="movie-category">
        <button type="submit">Append the movie to file</button>
    </form>
    
    <table id="showcase">
        <tr class="movie">
            <td class="movie-spec"></td>
            <td class="movie-spec"></td>
        </tr>
        <tr class="movie">
            <td class="movie-spec"></td>
            <td class="movie-spec"></td>
        </tr>
    </table>
    
    <script type="text/javascript">
        
        //The part i need help
    
    </script>
    </body>
    </html>

Well, saving data with JavaScript is fairly easy to achieve:

    // Save as File
    function download(filename, text) {
      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);
    }

Call with:

var csvContents = "1,2,3,4,5";
download("mydata.csv", csvContents);

You will need to figure out how csvContents will be constructed though.

I would advise you to learn jQuery as it is very easy for modifying or creating HTML/DOM elements (which is what you require here). Note that this is from someone who is by no means a web application expert and is from a different domain.

NOTE: If you want to append to the file, you need permissions, which you don't have over the your system from a browser. You should consider using a database.

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