使用jQuery在发布之前修改POST变量

aid*_*dan 42 forms jquery post

我在jQuery中有一个表单和一个提交处理程序.

当用户提交表单时,我想在POST请求之前修改(添加)一些参数,然后再从客户端发送到服务器.

  1. 用户点击"提交"
  2. 我的jQuery提交hander开始执行...
  3. 我创建了一些新的键/值对并将它们添加到POST有效负载中

目前,看起来我唯一的选择是使用$.post(),或$('form').append('<input type="hidden" name=... value=...');

谢谢你的帮助.

编辑:我已经在表单中附加了一个提交处理程序; 我正在尝试在用户单击提交按钮和发送到服务器的请求之间编辑post vars.

kei*_*ant 46

使用submit()表单上的函数创建回调.如果函数返回true,则表单将被提交; 如果为false,表单将不会发布.

$('#theForm').submit(function() {
    $("#field1").val(newValue1);
    $("#field2").val(newValue2);
    $(this).append(newFormField);
    return true;
});
Run Code Online (Sandbox Code Playgroud)

等等

  • 这听起来是最好的选择.虽然我必须动态创建大量隐藏的输入. (2认同)

小智 20

高级视图:
当表单以本机方式提交时,它是浏览器执行的最后一个操作,并且它在渲染引擎/ javascript解释器的范围之外执行.

任何通过JavaScript拦截实际POST或GET请求的尝试都是不可能的,因为这种传统的Web请求仅在浏览器引擎和网络子系统之间发生.

现代解决方案:
Web开发人员使用XMLHttpRequest(一种允许JavaScript解释器访问浏览器网络子系统的Web浏览器API)提交表单数据变得越来越流行.
This is commonly referred to as Ajax

一个简单但常见的用途看起来像:

<html>
  <form id="myForm" onsubmit="processForm()">
   <input type="text" name="first_name"/>
   <input type="text" name="last_name"/>
   <input type="submit" value="Submit">
  </form>

  <!--Using jQuery and Ajax-->
  <script type="text/javascript">
    /**
     * Function is responsible for gathering the form input data, 
     * adding additional values to the list, and POSTing it to the
     * server via Ajax.
     */
    function processForm() {
      //Retreive the data from the form:
      var data = $('#myForm').serializeArray();

      //Add in additional data to the original form data:
      data.push(
        {name: 'age',      value: 25},
        {name: 'sex',      value: 'M'},
        {name: 'weight',   value: 200}
      );

      //Submit the form via Ajax POST request:
      $.ajax({
        type: 'POST',
        url:  'myFormProcessor.php',
        data:  data,
        dataType: 'json'
      }).done(function(data) {
        //The code below is executed asynchronously, 
        //meaning that it does not execute until the
        //Ajax request has finished, and the response has been loaded.
        //This code may, and probably will, load *after* any code that
        //that is defined outside of it.
        alert("Thanks for the submission!");
        console.log("Response Data" +data); //Log the server response to console
      });
      alert("Does this alert appear first or second?");
    }
  </script>
</html>
Run Code Online (Sandbox Code Playgroud)

本机方法: 在存在XMLHttpRequest之前,一种解决方案是简单地将任何其他表单数据直接附加到文档.

使用上面发布的相同表单,jQuery append方法可能如下所示:

<html>
  <form action="myFormProcessor.php" method="POST" id="myForm" onsubmit="return processForm()">
    <input type="text" name="first_name"/>
    <input type="text" name="last_name"/>
    <input type="submit" value="Submit">
  </form>

 <script type="text/javascript">
  /**
   * Function is responsible for adding in additional POST values
   * by appending <input> nodes directly into the form.
   * @return bool - Returns true upon completion to submit the form
   */
  function processForm() {
    $('<input>').attr('type', 'hidden').attr('name', 'age').attr('value', 25).appendTo('#myForm');
    $('<input>').attr('type', 'hidden').attr('name', 'sex').attr('value', 'M').appendTo('#myForm');
    $('<input>').attr('type', 'hidden').attr('name', 'weight').attr('value', 200).appendTo('#myForm');

    return true; //Submit the form now 
    //Alternatively you can return false to NOT submit the form.
  }
 </script>
</html>
Run Code Online (Sandbox Code Playgroud)