Can a html button perform a POST request?

后端 未结 4 1068
庸人自扰
庸人自扰 2020-12-12 19:44

I want a submit type button to send a POST request.

I am thinking about something like this:

4条回答
  •  离开以前
    2020-12-12 20:12

    You can do that with a little help of JS. In the example below, a POST request is being submitted on a button click using the fetch method:

    const button = document.getElementById('post-btn');
    
    button.addEventListener('click', async _ => {
      try {     
        const response = await fetch('yourUrl', {
          method: 'post',
          body: {
            // Your body
          }
        });
        console.log('Completed!', response);
      } catch(err) {
        console.error(`Error: ${err}`);
      }
    });

提交回复
热议问题