提问者:小点点

将JSON数据通过Form.Submit()发送到服务器


我正在尝试使用POST提交表单,但我有一些来自

标记的额外数据,这些数据已存储到JS对象中。当我从JavaScript中点击form.submit()时,我想把它发送到服务器。

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

<a id="submit" type="button">Submit</a>

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

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

我尝试做的是用submit事件发送数据


共2个答案

匿名用户

标题中的JSON似乎不相关

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

null

$("#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>

匿名用户

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

null

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>