簡體   English   中英

如何將輸入字段HTML中的數據追加(存儲)到Json文件

[英]How to Append(store) data from input field Html to a Json File

當我單擊html輸入表單中的“插入”按鈕時,我想將HTML輸入表單中的某些數據保存(存儲)到DB.Json文件中!

這就是我的HTML:

<table id="datatable" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Age</th>  
<th>Birthday</th>
<th>Action</th>
</tr>
</thead>
<tr>
<td><input type="text" name="first_name" id="first_name"></td>
<td><input type="text" name="last_name" id="last_name"></td>
<td><input type="text" name="age" id="age"></td>
<td><input type="text" name="birthday" id="birthday"></td>
<td><button type="button" onclick="insert1()">Insert</button></td>
</tr>

現在,當我填寫html索引上的所有字段並單擊插入按鈕時,需要將這些數據保存在json文件中

首先,將您的<tr>放在<tbody> (這始終是一個好習慣)。

現在關於您的問題。 您無法使用javascript創建單獨的DB.json文件,但可以創建JSON對象並在其中存儲值。

然后只需通過獲取每個輸入id值來構建Json Object

 function insert1() { myJson = { first_name: $("#datatable").find("#first_name").val(), last_name: $("#datatable").find("#last_name").val(), age: $("#datatable").find("#age").val(), birthday: $("#datatable").find("#birthday").val(), }; console.log("myJson", myJson); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="datatable"> <thead> <tr> <th>Name</th> <th>Surname</th> <th>Age</th> <th>Birthday</th> <th></th> </tr> </thead> <tbody> <tr> <td><input type="text" name="first_name" id="first_name"></td> <td><input type="text" name="last_name" id="last_name"></td> <td><input type="text" name="age" id="age"></td> <td><input type="text" name="birthday" id="birthday"></td> <td><button type="button" onclick="insert1()">Insert</button></td> </tr> </tbody> </table> 

您可以使用axios寫入json文件

只是一個ajax包裝器

axios.post("json file path", jsonObject).then(
  res => console.log(res); /// successfully writing in file
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM