Pass extra variable when submitting a form using jQuery

前端 未结 5 2176
野性不改
野性不改 2021-02-12 12:53

I have a form in which the Submit button does not sit within the

tags. The submit button has an click handler to submit the form via jQuer
5条回答
  •  北荒
    北荒 (楼主)
    2021-02-12 13:35

    Jesse's answer is the only way to accomplish this via POST. You could also append the variable to the form's action value, but that would be passing that param via GET instead of POST. Without a hidden input appended to the form prior to allowing the default browser "submit" action, there is no way to access the raw post data of the HTTP request before it's been submitted - it's a chicken before the egg dilemma - what you're intending to do is change the HTTP POST data/headers that get sent to the next page, but the only way that data exists prior to the browser posting the data to the next page is by having the input tags embedded within the form element.

    An alternative solution you could go with would be to use the $.post() function to send whatever data you want via post during the onsubmit handler, and in the success handler redirect to the page you want. I know this doesn't go according to the rules above, but is another possible solution to a problem none the less.

    If you want to get real crazy though and follow all your rules, you could also:

    1. "clone" a hidden version the form to the DOM
    2. inject the submit button into the form
    3. trigger a click event on the injected submit button in the cloned form.

提交回复
热议问题