客观的FrameWork used : ElectronJS
我要采用用户提交的表单,并使用NodeJS脚本在客户端PC上生成JSON
文件。 json文件将具有key and value pairs
。
请参阅下面的预期输出。
的HTML
<form id="form" method="POST" action="#">
<div class="form-group col-auto">
<input type="text" class="form-control" id="username" name="username" placeholder="Enter Username" value="">
</div>
<div class="form-group col-auto">
<input type="text" class="form-control" id="account" name="account" placeholder="Enter Account" value="">
</div>
<button type="submit" id="save" class = "btn text-white mb-0"> Save </button>
</form>
JSdocument.getElementById("save").addEventListener('click', saveJSON(e))
async function saveJSON(e){
e.preventDefault()
var userData = document.getElementById('username').value
var acctData = document.getElementById('account').value
var formData = userData + acctData;
console.log(formData);
await writer.jsonWriter(formData);
//Error - Uncaught TypeError: Cannot read property 'value' of undefined.
错误这是我面临的错误
NodeJS脚本
async function jsonWriter(data){
let element = JSON.stringify(data);
fs.writeFileSync(__dirname + '\\data\\auth.json', element)
}
module.exports.jsonWriter = jsonWriter;
要求的输出// auth.json
{"username":"Stack","account":"Overflow"}
最佳答案
我相信您如何将事件传递到函数中并尝试调用preventDefault()
时存在问题。我使用async
关键字将函数直接放在事件监听器方法上。
如前所述,document.querySelector()
使用CSS选择器,而不是document.getElementById()
。在您的情况下,我会坚持按输入元素的ID获取输入元素。
就像Paul在回答中所说的那样,您需要一个JavaScript对象才能使JSON.stringify()正常工作。
document.getElementById("save").addEventListener('click', async function(e) {
e.preventDefault()
var userData = document.getElementById('username').value
var acctData = document.getElementById('account').value
var formData = {
username: userData,
account: acctData
}; // create JS object
console.log(JSON.stringify(formData));
});
<form id="form" method="POST" action="#">
<input type="text" id="username" name="username" placeholder="Enter Username">
<input type="text" id="account" name="account" placeholder="Enter Account">
<button type="submit" id="save">Save</button>
</form>
关于javascript - 使用JavaScript获取HTML表单值并将其保存到JSON键和值对中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64139655/