简体   繁体   English

提交带有一些其他参数的表单(post,而不是ajax)

[英]Submitting a form (post, NOT ajax) with some additional parameters

I need to perform a non-ajax post by clicking the submit of a form. 我需要通过单击表单提交来执行非ajax发布。 Before submiting I have to add some additional form parameters. 在提交之前,我必须添加一些其他表单参数。 Here is how I do this: 这是我的操作方法:

  $("#my_form").on("submit", function (e) {
    e.preventDefault();
    var data = $(this).serializeArray();
    data.push({"name": "extra data1", "value": "extra value 1"});
    var params = $.param(data);
    //what's next?
    //$.post($(this).attr("action"), data: params); // ajax request, I don't need an ajax request
  });

But how do I actually submit the form so it will send not only its parametes, but the additional ones I've added to it as well? 但是,我实际上如何提交表单,以便它不仅可以发送其参数,还可以发送我添加到其中的其他参数? Obviously, $(this).submit(); 显然, $(this).submit(); won't do this. 不会这样做。

You can use hidden inputs for this purpose. 您可以为此使用隐藏的输入。 Add

<INPUT TYPE='hidden' NAME='param1' VALUE='data1' ID='param1'>

and this will be submitted to php. 并将其提交给php。

You can change value of this fields from jQuery by 您可以通过以下方式从jQuery更改此字段的值:

$('#param1').value = 'data12';

You might want to see this SO question : Jquery - Create hidden form element on the fly 您可能想看一下这样的问题: jQuery-快速创建隐藏的表单元素

In your case, I guess you can do somethig like this to add a hidden input: 就您而言,我想您可以执行以下操作以添加隐藏的输入:

$("#my_form").on("submit", function (e) {

   $('<input>').attr({
        type: 'hidden',
        name: 'extra data1',
        value: 'extra value 1'
    }).appendTo($(this));  

});

DEMO: http://jsfiddle.net/naokiota/XyLUV/ 演示: http : //jsfiddle.net/naokiota/XyLUV/


Or, you could do the same thing like this: 或者,您可以执行以下操作:

$("#my_form").on("submit", function (e) {

   $('<input type="hidden" name="extra data1" value="extra value 1">')
   .appendTo($(this));

});

DEMO: http://jsfiddle.net/naokiota/Kkq6F/1/ 演示: http : //jsfiddle.net/naokiota/Kkq6F/1/

Hope this helps. 希望这可以帮助。

无需将数据从表单中拉出然后处理您得到的数据结构,只需在提交表单之前将隐藏的输入元素添加到表单即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM