使用jQuery提交表单时传递额外的变量 [英] Pass extra variable when submitting a form using jQuery
问题描述
我有一个表单,其中提交"按钮不在<form>
标记内.提交按钮具有click
处理函数,可通过jQuery的submit()
事件提交表单.效果很好.
I have a form in which the Submit button does not sit within the <form>
tags. The submit button has an click
handler to submit the form via jQuery's submit()
event. This works perfectly.
但是,我还需要对Submit按钮的值进行POST.由于该按钮在<form>
标记中不存在,因此不包含在POST数组中.因此,我需要设计一种在提交表单时传递额外变量的方法.
However, I need the value of the Submit button to be POST'ed as well. Since the button does not exist within the <form>
tags, it is not included in the POST array. Therefore, I need to engineer a way to pass an extra variable when the form is submitted.
关于无法实现此目标的一些规定包括:
Some stipulations on what cannot happen to achieve this include:
- 提交"按钮不能在
<form>
标记内移动. - 它不能使用jQuery
ajax
,post
或get
方法. - 它不能具有隐藏的
input
字段,也不能提交CSS隐藏的提交按钮. - 该表单的行为必须与表单中正常的提交"按钮完全一样.
- The Submit button cannot be moved within the
<form>
tags. - It cannot use the jQuery
ajax
,post
, orget
methods. - It cannot have hidden
input
fields or submit buttons hidden by CSS. - The form must act exactly as if there was a normal Submit button in the form.
我设想过类似的事情,但是显然这是行不通的.
I envisioned something like, but obviously this does not work.
$('#admin_form').submit({'variable_name', 'true'});
有人对我如何实现这一目标有任何想法吗?
Anybody have any ideas on how I could achieve this?
推荐答案
您可以做的一件事是使用onsubmit
属性,使javascript将一个post字段注入到表单中,并按原样提交按钮的值.已提交.您必须使用隐藏的输入字段来执行此操作,但是您只能在用户单击提交"按钮之后立即添加输入字段-这样输入字段从一开始就不存在(希望这可以满足您的要求).像这样:
One thing you could do is use the onsubmit
attribute to have javascript inject a post field into the form with the value of the submit button right as it is submitted. You'd have to do this with a hidden input field, but you'd only add the input field right after the user clicked the submit button -- so the input field wouldn't exist there from the beginning (hopefully this satisfies your requirements). So something like:
function submitHandler()
{
submitVal = $('#submitButton').val();
$('#myForm').append("<input type='hidden' name='submitValue' value='"+
submitVal+"' />");
return true;
}
在单击按钮时,它会保留附加值.
Which would stick in the extra value right as the button was clicked.
这篇关于使用jQuery提交表单时传递额外的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!