使用 jQuery 提交表单时传递额外的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5097184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:34:21  来源:igfitidea点击:

Pass extra variable when submitting a form using jQuery

jqueryformspost

提问by Michael Irigoyen

I have a form in which the Submit button does not sit within the <form>tags. The submit button has an clickhandler to submit the form via jQuery's submit()event. This works perfectly.

我有一个表单,其中提交按钮不在<form>标签内。提交按钮有一个click处理程序通过 jQuery 的submit()事件提交表单。这完美地工作。

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.

但是,我也需要提交按钮的值。由于该按钮不存在于<form>标签中,因此它不包含在 POST 数组中。因此,我需要设计一种在提交表单时传递额外变量的方法。

Some stipulations on what cannot happen to achieve this include:

关于无法实现这一目标的一些规定包括:

  • The Submit button cannot be moved within the <form>tags.
  • It cannot use the jQuery ajax, post, or getmethods.
  • It cannot have hidden inputfields or submit buttons hidden by CSS.
  • The form must act exactly as if there was a normal Submit button in the form.
  • 提交按钮不能在<form>标签内移动。
  • 它不能使用jQuery的ajaxpostget方法。
  • 它不能有隐藏input字段或提交由 CSS 隐藏的按钮。
  • 表单的行为必须与表单中的普通提交按钮完全一样。

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?

有人对我如何实现这一目标有任何想法吗?

回答by Jesse Cohen

One thing you could do is use the onsubmitattribute 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:

您可以做的一件事是使用该onsubmit属性让 javascript 将一个 post 字段注入到表单中,并在提交时将提交按钮的值插入到表单中。您必须使用隐藏的输入字段来执行此操作,但您只能在用户单击提交按钮后立即添加输入字段 - 因此输入字段从一开始就不存在(希望这满足您的要求)。所以像:

 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.

当按钮被点击时,它会保留额外的值。

回答by AsGoodAsItGets

This seems to be an old question, but since I just ran into a similar issue and found a good solution (for me), I thought I'd post it:

这似乎是一个老问题,但由于我刚刚遇到了类似的问题并找到了一个很好的解决方案(对我来说),我想我会发布它:

 $('#admin_form').trigger('submit', [ { 'variable_name': true } ]);

or

或者

$('#admin_form').trigger('submit', [ 'variable_name', 'true' ]);

depending on whether you want to pass a variable called variable_namewith value trueor you want to pass 2 separate variables.

取决于您是要传递variable_name带有值的变量true还是要传递 2 个单独的变量。

And just to be clear, this will not of course automatically submit variable_namewith the rest of the form fields, but if you have a submit handler, as I do in jQuery, the variables will be passed as arguments, after the event.

需要说明的是,这当然不会variable_name与其余的表单字段一起自动提交,但是如果您有一个提交处理程序,就像我在 jQuery 中所做的那样,变量将在事件之后作为参数传递。

回答by streetlogics

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.

Jesse 的回答是通过 POST 完成此任务的唯一方法。您还可以将变量附加到表单的操作值,但这将通过 GET 而不是 POST 传递该参数。如果没有在允许默认浏览器“提交”操作之前附加到表单的隐藏输入,则无法在提交之前访问 HTTP 请求的原始帖子数据 - 这是鸡蛋困境之前的鸡 - 你是什么打算做的是更改发送到下一页的 HTTP POST 数据/标头,但在浏览器将数据发布到下一页之前数据存在的唯一方法是将输入标签嵌入表单元素中。

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.

您可以采用的另一种解决方案是使用 $.post() 函数在 onsubmit 处理程序期间通过 post 发送您想要的任何数据,并在成功处理程序中重定向到您想要的页面。我知道这不符合上述规则,但仍然是解决问题的另一种可能方法。

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.
  1. “克隆”一个隐藏版本的表单到 DOM
  2. 将提交按钮注入表单
  3. 在克隆表单中的注入提交按钮上触发点击事件。

回答by Helen Connole

If you wanted to do it straight from an element which was changed without writing a submit handler, this works:

如果您想直接从已更改的元素中执行此操作,而无需编写提交处理程序,则可以这样做:

<script>
$(function() {
  $( ".datePicker" ).datepicker({ 
      dateFormat: 'dd-M-yy',
      onSelect: function (date) {   
        $('#dateChanger').append("<input type='hidden' name='changed_" + $(this).attr("name") + "' value='" + $(this).attr("value") + "' />");    
        $("#dateChanger").submit();
  }
  });
});
</script>

回答by nyluje

On jquery 1.11.1

在 jquery 1.11.1 上

I've managed it like that:

我是这样管理的:

$(yourForm).on('submit',{'yourExtraData':extraData},function(event){
        alert('your extra data ' + event.data['yourExtraData'] + ' went thru');
});

Check also: https://api.jquery.com/event.data/

检查:https: //api.jquery.com/event.data/