HTML form - POST or GET depending on button clicke

2019-08-23 11:46发布

问题:

Let there be a search form with quite many of the input fields. The user may either click:

  • [Search] and GET the list of the results,
  • [Save search criteria] for future use and POST the form content to be stored on server (I'm not interested in storing locally in cookies or so).

How do I achieve that? I've only found solutions to make two types of POST request on two separate buttons.

Maybe a JavaScript onclick function to set <form method="??"> right before its submitted? Would that work?

回答1:

In HTML5, the <input> element got some new attributes

<input type="submit" formmethod="post" formaction="save.php" value="Save" />
<input type="submit" formmethod="get" formaction="search.php" value="Search" />

The same attributes are valid for <button>



回答2:

Yes you can change form method before submit form using jquery

<form method="POST" id="myForm">
    <button onclick="changeMethod()">submit</button>
</form>

Function changeMethod in jquery

function changeMethod(){
    $("#myForm").attr("method", "get");
}