javascript - How can I use form input values in my submission script?
问题描述
I'm trying to do a simple thing. I have a website and I want people to be able to send some feedback and warn me, for that i have a "Notify Owner" button which displays a form and on Submit should execute a python script that send myself an email with the information they filled.
This is my form code (index.html - Created on the client side)
<script>
async function notifyOwner() {
await fetch("api/notify", { method: "post" }).catch(console.log);
}
</script>
<div class="form-popup" id="myForm">
<form class="form-container" name="form-owner">
<h1>Notify Owner</h1>
<label><b>Name</b></label>
<input id="name" style="width:90%" type="text" placeholder="Enter your name$
<label><b>Message</b></label>
<input id="context" style="width:90%" type="text" placeholder="Enter Reason$
<button type="submit" class="btn" onclick="notifyOwner()">Submit</button>
<button type="button" class="btn cancel" onclick="closeForm()">Close</butto$
</form>
</div>
This is my server side handling
app.post("/api/notify", async (req, res) => {
try{
var subject = "teste";
var body = "ok";
child_process.execSync('python3 sendEmail.py ' + subject + " " + body);
}catch(error){
console.error(error);
}
});
what should I do to replace the var subject with the value from id="name" and replace the var body with the value from id="context"?
解决方案
SOLVED
On the server side.
app.use(express.json());
app.post("/api/notify", async (req, res) => {
try{
const subject = req.body.sub;
const body = req.body.cont;
child_process.execSync('python3 sendEmail.py ' + subject + " " + body);
}catch(error){
console.error(error);
}
});
On the client side.
<script>
async function notifyOwner(ele) {
const name = document.getElementById("name");
const context = document.getElementById("context");
await fetch("api/notify", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({sub: name.value, cont: context.value})
}).catch(console.log);
}
</script>
<button type="submit" class="btn" onclick="notifyOwner(this)">Submit</button>
推荐阅读
- package - 如何使用“添加”命令更改下载包的默认保存位置?
- javascript - 使用 JS 将 html 数据保存到 .xlsx
- java - 配置为监听 127.0.0.1 时无法访问在 Docker 容器中运行的 Tomcat
- compression - 压缩文件(例如 zip 或 7z)然后使用奇偶校验生成器再次扩展以进行文件恢复是否有意义?
- c# - 使用现有的 ml.net 模型进行预测,使用 json 作为模型输入
- javascript - 如何在同步等待的同一函数中使用 fetch 和 fetch 的结果
- php - 使用 PHP 从 MySQL 表中计算不同的值
- wordpress - DIVI 主题,克隆页面选项未列出可用页面。(elegentthemes.com 拒绝连接)
- java - 如何在不更改 Postman 中自动生成的主键的情况下更新记录中的值?
- javascript - 当 autoPlay=true 时,如何取消延迟加载的 Wistia 嵌入?