【问题标题】:How to append data to request form.submit()如何将数据附加到请求 form.submit()
【发布时间】:2021-06-04 18:46:10
【问题描述】:

我正在尝试使用 POST 提交表单,但我有一些来自 <p> 标记的附加数据,这些数据已存储到 JS 对象中。当我从 JavaScript 中点击 form.submit() 时,我想将其发送到服务器。

<p> the text i want to send </p>
<form action="url" id="invoice-form">
    <input type="text" name="input"> 
</form>


Edit:[Updated Title]
<a id="submit" type="button">Submit</a>

<script>
let data = $('p').text()

$('#invoice-form').submit()

我想要做的是发送datasubmit 事件

【问题讨论】:

  • 标题中的“JSON”引用是什么意思?
  • 我将使用 .stringify() 将 JS 对象转换为 JSON 后将数据发送到服务器

标签: javascript jquery json forms


【解决方案1】:

您可以将onclick 处理程序附加到按钮并使用fetch 将JSON 格式的数据发送到服务器。

const onclick = (e) => {
  const data = {
    data: document.querySelector('input').value
  }


  e.preventDefault();

  fetch("/server-end-point", {
    method: 'POST',
    mode: 'no-cors',
    cache: 'no-cache',
    credentials: 'same-origin',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
}

const button = document.querySelector('#submit');

button.onclick = onclick;
<p> the text i want to send </p>
<form action="url" id="invoice-form">
    <input type="text" name="input"> 
    <button id="submit" type="button">Submit</button>
</form>

有关 Fetch 的更多信息: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
您的浏览器目标是否支持 fetch: https://caniuse.com/fetch

【讨论】:

  • 我很欣赏您的回复,但我想同步进行,这就是为什么我没有使用它,因为它的工作性质。
【解决方案2】:

标题中的 JSON 似乎不相关

  1. 将链接更改为提交按钮
  2. 添加复制数据的提交事件处理程序
  3. 允许提交发送到服务器

$("#invoice-form").on("submit", function(e) {
  let data = $('p').text()
  $("#input").val(data)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p> the text i want to send </p>
<form action="url" id="invoice-form">
  <input type="text" name="input" id="input">
  <input type="submit">
</form>

如果要 Ajax 值,只需更改为这个

$("#invoice-form").on("submit", function(e) {
  e.prevenDefault();
  let data = $('p').text()
  $.post(this.action,{"input":data})
});

【讨论】:

  • 问这么简单的问题我觉得很傻。
  • 我想同步,你的回答就可以了。谢谢@mplungjan
  • @Andreas 更新了解释
  • 有没有办法将数据传递到 QueryDICT 中??
猜你喜欢
  • 2012-05-02
  • 1970-01-01
  • 2021-08-03
  • 1970-01-01
  • 2016-03-30
  • 2016-08-15
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
相关资源
最近更新 更多