提交之前添加POST参数

我有这个简单的forms:

<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() } ]; 

请不要修改表格。

要添加使用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; }); 

以前的答案可以缩短 ,更易读

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

如果你想在不修改表单的情况下添加参数,你必须序列化表单,添加你的参数并用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()文档。

你可以做一个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") } }); 

纯粹的JavaScript:

创buildXMLHttpRequest:

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

JavaScript函数通过POST发送信息:

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

你可以做一个阿贾克斯电话。

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

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