POST Request with Fetch API?

后端 未结 5 1730
鱼传尺愫
鱼传尺愫 2020-12-01 03:10

I know that with the new Fetch API (used here with ES2017\'s async/await) you can make a GET request like this:

async getData() {
          


        
5条回答
  •  天涯浪人
    2020-12-01 03:29

    The best way to POST form data to a PHP-script is the Fetch API. Here is an example:

    function postData() {
        const form = document.getElementById('form');
        let data = new FormData();
        data.append('name', form.name.value);
    
        fetch('../php/contact.php', {method: 'POST', body: data}).then(response => {
            if (!response.ok){
                throw new Error('Network response was not ok.');
            }
        }).catch((err) => {
        	console.log(err);
        });
    }

    Here is a very basic example of a PHP-script that takes the data and sends an email:

提交回复
热议问题