如何在提交前添加额外的字段?

时间:2022-11-24 19:39:13

Is there a way to use javascript and JQuery to add some additional fields to be sent from a HTTP form using POST?

是否有一种方法可以使用javascript和JQuery添加一些附加字段来使用POST从HTTP表单发送?

I mean:

我的意思是:

<form action="somewhere" method="POST" id="form">
    <input type="submit" name="submit" value="Send" />
</form>

<script type="text/javascript">

    $("#form").submit( function(eventObj) 
        {
            // I want to add a field "field" with value "value" here
            // to the POST data

            return true;
        }
</script>

5 个解决方案

#1


110  

Yes.You can try with some hidden params.

是的。你可以尝试一些隐藏的参数。

  $("#form").submit( function(eventObj) {
      $('<input />').attr('type', 'hidden')
          .attr('name', "something")
          .attr('value', "something")
          .appendTo('#form');
      return true;
  });

#2


32  

Try this:

试试这个:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="field_name" value="value" /> ');
    return true;
});

#3


9  

You can add a hidden input with whatever value you need to send:

您可以添加一个隐藏的输入,您需要发送的任何值:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="someName" value="someValue">');
    return true;
});

#4


6  

$('#form').append('<input type="text" value="'+yourValue+'" />');

#5


-1  

This works:

如此:

var form = $(this).closest('form');

form = form.serializeArray();

form = form.concat([
    {name: "customer_id", value: window.username},
    {name: "post_action", value: "Update Information"}
]);

$.post('/change-user-details', form, function(d) {
    if (d.error) {
        alert("There was a problem updating your user details")
    } 
});

#1


110  

Yes.You can try with some hidden params.

是的。你可以尝试一些隐藏的参数。

  $("#form").submit( function(eventObj) {
      $('<input />').attr('type', 'hidden')
          .attr('name', "something")
          .attr('value', "something")
          .appendTo('#form');
      return true;
  });

#2


32  

Try this:

试试这个:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="field_name" value="value" /> ');
    return true;
});

#3


9  

You can add a hidden input with whatever value you need to send:

您可以添加一个隐藏的输入,您需要发送的任何值:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="someName" value="someValue">');
    return true;
});

#4


6  

$('#form').append('<input type="text" value="'+yourValue+'" />');

#5


-1  

This works:

如此:

var form = $(this).closest('form');

form = form.serializeArray();

form = form.concat([
    {name: "customer_id", value: window.username},
    {name: "post_action", value: "Update Information"}
]);

$.post('/change-user-details', form, function(d) {
    if (d.error) {
        alert("There was a problem updating your user details")
    } 
});