不正确地以html发送表单数据

问题描述 投票:0回答:1

所以我想发送任何我在输入栏中输入的内容,然后通过post方法发送到任何api链接。但是无论何时发送,我都会得到{}。问题是当我不在输入栏中发送任何内容时,也就是空白,然后按提交,我仍然得到{}。但是当我输入乱码时,它仍然{}。所以我想我输入的内容都不会发送到api链接。

[另外,当我硬编码body: JSON.stringify(this.myForm)之类的内容时,它也会在后端显示为响应。因此,我相信我的提取请求中存在这一错误。这是我的代码,我应该为身体放置些什么。

<html>

<body>
  <h1>Draft V0.1</h1>

  <form class="form" id="myForm">
    <label for="skill">add skill</label>
    <input type="text" name="skill" id="skill">
    <button type="submit">Submit</button>
  </form>

  <script>
    const myForm = document.getElementById('myForm')


    myForm.addEventListener('submit', function (e) {
      e.preventDefault();

      const formData = new FormData(this);

      fetch('https://fj5s3i60a8.execute-api.us-east-1.amazonaws.com/updateSkill', {
        method: 'post',
        body: JSON.stringify(new FormData(myForm)),
        headers:
        {
          "Content-Type": "application/json; charset=utf-8",
          "Accept": 'application/json'
        }
      }).then(function (response) {
        console.log(response)
        return response.json();
      });
    });
  </script>

</body>

</html>
  • [请注意,我在盲目地玩弄身体,以查看可以解析的内容,但最终会出现cors错误。

提前谢谢您

javascript html fetch
1个回答
0
投票

window.addEventListener( "load", function () {
  function sendData() {
    const XHR = new XMLHttpRequest();

    // Bind the FormData object and the form element
    const FD = new FormData( form );

    // Define what happens on successful data submission
    XHR.addEventListener( "load", function(event) {
      alert( event.target.responseText );
    } );

    // Define what happens in case of error
    XHR.addEventListener( "error", function( event ) {
      alert( 'Oops! Something went wrong.' );
    } );

    // Set up our request
    XHR.open( "POST", "https://example.com/cors.php" );

    // The data sent is what the user provided in the form
    XHR.send( FD );
  }
 
  // Access the form element...
  const form = document.getElementById( "myForm" );

  // ...and take over its submit event.
  form.addEventListener( "submit", function ( event ) {
    event.preventDefault();

    sendData();
  } );
} );
<html>

<body>
  <h1>Draft V0.1</h1>

  <form class="form" id="myForm">
    <label for="skill">add skill</label>
    <input type="text" name="skill" id="skill">
    <button type="submit">Submit</button>
  </form>
  </body>
  </html>
热门问题
推荐问题
最新问题