【问题标题】:Adding POST parameters before submit提交前添加 POST 参数
【发布时间】:2010-11-02 21:22:41
【问题描述】:

我有这个简单的表格:

<form id="commentForm" method="POST" action="api/comment">
    <input type="text" name="name" title="Your name"/>
    <textarea  cols="40" rows="10" name="comment" title="Enter a comment">
    </textarea>
    <input type="submit" value="Post"/>
    <input type="reset" value="Reset"/>
</form>

我需要在发送到服务器之前添加两个 POST 参数:

var params = [
               {
                 name: "url",
                 value: window.location.pathname
               },
               {
                  name: "time",
                  value: new Date().getTime()
               }
             ];

请不要修改表格。

【问题讨论】:

  • 附注:依赖用户提供有效时间和网址可能会导致问题。

标签: javascript jquery forms


【解决方案1】:

使用 Jquery 添加:

$('#commentForm').submit(function(){ //listen for submit event
    $.each(params, function(i,param){
        $('<input />').attr('type', 'hidden')
            .attr('name', param.name)
            .attr('value', param.value)
            .appendTo('#commentForm');
    });

    return true;
}); 

【讨论】:

  • 那是修改表格
  • @Hontoni 我们可以在将参数项附加到表单之前检查表单中是否存在,这样可以使参数项只附加一次。
  • 你可以使用myInput = document.createElement('input')然后将属性设置为对象,像这样:myInput.type = 'text'; myInput.name = 'name'
  • 那是修改表格。这是 IMO 的解决方案:stackoverflow.com/a/34566506/9258504
【解决方案2】:

你可以在没有 jQuery 的情况下做到这一点:

    var form=document.getElementById('form-id');//retrieve the form as a DOM element

    var input = document.createElement('input');//prepare a new input DOM element
    input.setAttribute('name', inputName);//set the param name
    input.setAttribute('value', inputValue);//set the value
    input.setAttribute('type', inputType)//set the type, like "hidden" or other

    form.appendChild(input);//append the input to the form

    form.submit();//send with added input

【讨论】:

    【解决方案3】:

    以前的答案可以缩短并且更可读

    $('#commentForm').submit(function () {
        $(this).append($.map(params, function (param) {
            return   $('<input>', {
                type: 'hidden',
                name: param.name,
                value: param.value
            })
        }))
    });
    

    【讨论】:

      【解决方案4】:

      如果要在不修改表单的情况下添加参数,则必须将表单序列化,添加参数并使用AJAX发送:

      var formData = $("#commentForm").serializeArray();
      formData.push({name: "url", value: window.location.pathname});
      formData.push({name: "time", value: new Date().getTime()});
      
      $.post("api/comment", formData, function(data) {
        // request has finished, check for errors
        // and then for example redirect to another page
      });
      

      请参阅 .serializeArray()$.post() 文档。

      【讨论】:

      • @MonneratRJ 不同意,因为用户从未指定他们想使用 ajax。我遇到了同样的问题,因为我不想使用 ajax。
      • @Alex ok 有道理... Pim Jager 的回答符合要求...
      • @Alex OP 说他们不想修改表单。
      • @MichałPerłakowski 是过于字面意思的案例之一。
      • “如果你想在不修改表单的情况下添加参数”我已经找了一段时间了!
      【解决方案5】:

      你可以做一个form.serializeArray(),然后在发布之前添加名称-值对:

      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")
          } 
      });
      

      【讨论】:

        【解决方案6】:

        纯 JavaScript:

        创建 XMLHttpRequest:

        function getHTTPObject() {
            /* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, 
               por lo que se puede copiar tal como esta aqui */
            var xmlhttp = false;
            /* No mas soporte para Internet Explorer
            try { // Creacion del objeto AJAX para navegadores no IE
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(nIE) {
                try { // Creacion del objet AJAX para IE
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(IE) {
                    if (!xmlhttp && typeof XMLHttpRequest!='undefined') 
                        xmlhttp = new XMLHttpRequest();
                }
            }
            */
            xmlhttp = new XMLHttpRequest();
            return xmlhttp; 
        }
        

        通过 POST 发送信息的 JavaScript 函数:

        function sendInfo() {
            var URL = "somepage.html"; //depends on you
            var Params = encodeURI("var1="+val1+"var2="+val2+"var3="+val3);
            console.log(Params);
            var ajax = getHTTPObject();     
            ajax.open("POST", URL, true); //True:Sync - False:ASync
            ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            ajax.setRequestHeader("Content-length", Params.length);
            ajax.setRequestHeader("Connection", "close");
            ajax.onreadystatechange = function() { 
                if (ajax.readyState == 4 && ajax.status == 200) {
                    alert(ajax.responseText);
                } 
            }
            ajax.send(Params);
        }
        

        【讨论】:

          【解决方案7】:

          您可以进行 ajax 调用。

          这样,您就可以通过 ajax 'data:' 参数自己填充 POST 数组

          var params = {
            url: window.location.pathname,
            time: new Date().getTime(), 
          };
          
          
          $.ajax({
            method: "POST",
            url: "your/script.php",
            data: params
          });
          

          【讨论】:

          • 你应该展示一个例子。你可以使用SO的嵌入式sn-ps轻松做到这一点
          猜你喜欢
          • 2023-04-08
          • 2016-05-22
          • 2018-05-30
          • 1970-01-01
          • 1970-01-01
          • 2014-03-26
          • 1970-01-01
          • 1970-01-01
          • 2013-01-27
          相关资源
          最近更新 更多