Can a html button perform a POST request?

后端 未结 4 1067
庸人自扰
庸人自扰 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 19:52

    This can be done with an input element of a type "submit". This will appear as a button to the user and clicking the button will send the form.

    <form action="" method="post">
        <input type="submit" name="upvote" value="Upvote" />
    </form>
    
    0 讨论(0)
  • 2020-12-12 20:00

    You can:

    • Either, use an <input type="submit" ..>, instead of that button.
    • or, Use a bit of javascript, to get a hold of form object (using name or id), and call submit(..) on it. Eg: form.submit(). Attach this code to the button click event. This will serialise the form parameters and execute a GET or POST request as specified in the form's method attribute.
    0 讨论(0)
  • 2020-12-12 20:12

    You need to give the button a name and a value.

    No control can be submitted without a name, and the content of a button element is the label, not the value.

    <form action="" method="post">
        <button name="foo" value="upvote">Upvote</button>
    </form>
    
    0 讨论(0)
  • 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}`);
      }
    });
    <button id="post-btn">I'm a button</button>

    0 讨论(0)
提交回复
热议问题