简体   繁体   English

如何通过JavaScript发送表单数据到API post

[英]How to send form data to API post via JavaScript

I have a form in my project and when it is submitted I need to send the data to an API and receive the response to check if there's an errors我的项目中有一个表单,提交后我需要将数据发送到 API 并接收响应以检查是否有错误

the html html

<form id="contactForm" class="w-75 mx-auto">
    <input type="text" class="form-control bg-transparent" placeholder="Name">
    <input type="email" class="form-control bg-transparent my-3" placeholder="E-mail">
    <textarea class="form-control bg-transparent" placeholder="Your Message"></textarea>
    <button type="submit" class="my-3 px-4 py-2 rounded-3">SEND</button>
</form>

the js js

$('#contactForm').submit(function (e) {
    e.preventDefault();

});

This should work.这应该工作。 Make sure URL for API and web should be the same else you could get cross site error:确保 URL 对应 API 和 web 应该相同,否则您可能会遇到跨站点错误:

<form id="contactForm" class="w-75 mx-auto" action="http://yourAPI.com">
    <input type="text" class="form-control bg-transparent" placeholder="Name">
    <input type="email" class="form-control bg-transparent my-3" placeholder="E-mail">
    <textarea class="form-control bg-transparent" placeholder="Your Message"></textarea>
    <button type="submit" class="my-3 px-4 py-2 rounded-3">SEND</button>
</form>

<script
  src="https://code.jquery.com/jquery-3.6.0.min.js"
  integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
  crossorigin="anonymous"></script>

<script>
    $('#contactForm').submit(function (e) {
        e.preventDefault(); // avoid to execute the actual submit of the form.

        
        var form = $(this);
        var url = form.attr('action');
        
        $.ajax({
            type: "POST",
            url: url,
            data: form.serialize(), // serializes the form's elements.
            success: function(data)
            {
                alert(data); // show server response 
            }
        });
    });
</script>

You can use fetch api and the POST method to send data to an api. Since you have not provided how your api works or how the data is to be passed I cannot provide further help, but i can guide you to the correct path.您可以使用fetch api 和POST方法将数据发送到 api。由于您没有提供您的 api 的工作原理或数据的传递方式,我无法提供进一步的帮助,但我可以指导您找到正确的路径。

Read more about fetch api in javascript 在 javascript 中阅读有关获取 api 的更多信息

(async function () {
    const url = ''; // your api endpoint here
    const res = await fetch(url, { method: 'POST' });
    // res corresponds to the api response;
})();

Since you're using jQuery, you should probably read jQuery post method由于您使用的是 jQuery,您可能应该阅读jQuery post 方法

$("#contactForm").submit( async (e) => {
    e.preventDefault();
    const data = {
        name: e.target.elements[0].value,
        email: e.target.elements[1].value,
        message: e.target.elements[2].value,
    }
    const response = await fetch(url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-Type': 'application/json'
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when- 
       downgrade, origin, origin-when-cross-origin, same-origin, strict- 
       origin, strict-origin-when-cross-origin, unsafe-url
       body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
})
let formData = new FormData();
formData.append('variable1', variable1);
formData.append('variable2', variable2);

url = `url`
options = {
  method: 'POST',
  body: formData
}

let response = await request(url, options)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM