【问题标题】:submit form along with request parameter连同请求参数一起提交表单
【发布时间】:2021-12-16 14:28:30
【问题描述】:

我想使用 javascript 将我的表单提交到后端。但是,我还必须向表单 url/action 端点添加一个可变参数。想知道 javascript 的执行方式是什么?

这就是我现在拥有的

<form id="profile-message-form" action="/send-message?to" method="get">
   <textarea name="message-content" id="message-content" maxlength="1000" contentEditable="true"></textarea>
   <div id="send-button-container">
       <button id="profile-message-submit" onclick="sendMessage('profile-message-form')" name="subject" type="submit"><i id="profile-message-send-icon" class="fas fa-paper-plane"></i><p>Send</p></button>
   </div>
</form>

function sendMessage(form_id) {
    var form = document.getElementById(form_id);
    // find email address to send to
    // submit form with email address as ":to" req param
    form.submit();
}

【问题讨论】:

  • 您从哪里获得电子邮件地址?

标签: javascript html frontend web-frontend


【解决方案1】:

最简单的方法是在提交之前将隐藏字段添加到表单中。

const formEl = document.getElementById('form');

formEl.onsubmit = e => {
  e.preventDefault();
  
  const hiddenAgeEl = document.createElement('input');
  hiddenAgeEl.type = 'hidden';
  hiddenAgeEl.name = 'age';
  hiddenAgeEl.value = 22;
  
  formEl.append(hiddenAgeEl);
  
  formEl.submit();
}
<form id="form" action="/send-message?to" method="get">
   <input type="text" name="name">
   <button type="submit">Submit</button>
</form>

【讨论】:

  • 试过这个,由于某种原因,现在当我在后端解析 req.body 时它是空的。恢复了更改,但奇怪的是它仍然是空的。它仅在我将表单方法更改为发布而不是获取时才修复
  • @masterghani,无法确定,但请查看 Content-Type 的方向。很可能您的服务器配置为在content-type: application/json 中获取数据,而我们默认发送application/x-www-form-urlencoded
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多