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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2647861/
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 13:57:36  来源:igfitidea点击:

Modify POST vars before post, using jQuery

jqueryformspost

提问by aidan

I have a form, and a submit handler in jQuery.

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

When the user submits the form, I want to modify (add) some parameters to the POST request, before it is despatched from the client to the server.

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

i.e.

IE

  1. User clicks 'submit'
  2. My jQuery submit hander begins execution...
  3. I create some new key/value pairs and add them to the POST payload
  1. 用户点击“提交”
  2. 我的 jQuery 提交处理程序开始执行...
  3. 我创建了一些新的键/值对并将它们添加到 POST 负载中

At the moment, it looks like my only options are to use $.post(), or $('form').append('<input type="hidden" name=... value=...');

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

Thanks for any help.

谢谢你的帮助。

Edit: I've already attached a submit handler to the form; I'm trying to edit the post vars in between the user clicking the submit button, and the request being sent to the server.

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

回答by keithjgrant

Use the submit()function on the form to create a callback. If the function returns true, the form will be submitted; if false, the form will not post.

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

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

etc.

等等。

回答by aidan

High Level View:
When a form is submitted natively, it is the very last operation a browser performs, and it is executed outside of the scope of the rendering engine/javascript interpreter.

Any attempts of intercepting the actual POST or GET request via JavaScript is impossible as this traditional web request occurs exclusively between the Browser Engine and the Networking Subsystem.

高级视图:
当表单被原生提交时,它是浏览器执行的最后一个操作,它在渲染引擎/javascript 解释器的范围之外执行。

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

Modern Solution:
It is becoming more popular for web developers to submit form data using XMLHttpRequest -- a web browser API that allows the JavaScript intepreter to access the browser networking subsystem.
This is commonly referred to as Ajax

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

A simple but common use of this would look something like:

一个简单但常见的用法如下所示:

<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>

Native Approach:Before the existence of XMLHttpRequest, one solution would be to simply append any additional form data directly to the document.

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

Using the same form posted as above, a jQuery append method could look like:

使用与上述相同的表单,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>

回答by boycy

I don't think you can modify the POST vars that way. When a submit handler runs there's no hash of the form data that really exists that you can add to or modify. I think you're right - your only options to $.post() yourself (which I'd recommend) or to append hidden inputs to the form (has the overhead of DOM modification which you don't really need).

我认为您不能以这种方式修改 POST 变量。当提交处理程序运行时,没有您可以添加或修改的真正存在的表单数据的散列。我认为你是对的 - 你唯一的选择是 $.post() 自己(我推荐)或将隐藏的输入附加到表单(具有你并不真正需要的 DOM 修改开销)。

回答by Hao XU

I have been working on this question for one day, and I come up with a good solution:

这个问题我研究了一天,我想出了一个很好的解决方案:

you could use Jquery .clone() to create a copy of the form you want to submit. Then you could do the modifications on the copy, and finally submit the copy.

您可以使用 Jquery .clone() 创建要提交的表单的副本。然后您可以对副本进行修改,最后提交副本。

回答by Tom

Attach a submit() handler to the form.

将 submit() 处理程序附加到表单。

$('form#myForm').submit(myPostHandlingFunction);

Then submit/ do the post from your function. The easiest thing would be to just populate a couple of hidden inputs in the form and then return true to allow the submit to happen if everything looks right.

然后从您的功能提交/执行帖子。最简单的方法是在表单中填充几个隐藏的输入,然后返回 true 以允许在一切正常时提交。

回答by Jay

You can hook the click event of the submit button and do your processing there. For the key/value pairs you might try a hidden form element.

您可以挂钩提交按钮的点击事件并在那里进行处理。对于键/值对,您可以尝试隐藏表单元素。

回答by Franco Ugarte

$("#frm").submit(function (e) {
    e.preventDefault();
    form = document.getElementById("frm"); //$("#frm")

    $.each(form.elements, function (i, el) {
        el.name = your_new_name;
        el.value = your_new_value;
        //... //el.type, el.id ...
    });

    form.submit();

    return true;
});

回答by anon2020202020

$('#myForm').submit(function() {
  $.each(this, function (i, element) {
    console.log("element name " + element.name + ", element val: " + element.value);
    if(element.name="thisThingInParticular")
      element.value = "myNewValueForThisElementInParticular";
    )

  }
});