提问者:小点点

如何在提交脚本中使用表单输入值?


我在做一件简单的事。我有一个网站,我希望人们能够发送一些反馈和警告我,因为我有一个“通知所有者”按钮,它显示一个表单,提交时应该执行一个python脚本,给我自己发送一封电子邮件与他们填写的信息。

这是我的表单代码(index.html-在客户端创建)

<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>

这是我的服务器端处理

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);
  }
});

要将var主题替换为id=“name”中的值,并将var主体替换为id=“context”中的值,我应该怎么做?


共1个答案

匿名用户

在客户端脚本标记中:

async function notifyOwner(ele) {
  await fetch("api/notify", { 
    method: "POST",
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({id: ele.parentElement.parentElement.getAttribute('id')})
  }).catch(console.log);
}

HTML:

...
        <button type="submit" class="btn" onclick="notifyOwner(this)">Submit</button>
...

传递给NotifyOwner

在服务器中:

app.use(express.bodyParser());

app.post("/api/notify", async (req, res) => {
  try{
    var subject = req.body.id; // Get id key
    var body = "ok";
    child_process.execSync('python3 sendEmail.py ' + subject + " " + body);
  }catch(error){
    console.error(error);
  }
});