dfa*_*dfa 64 javascript forms jquery
我有这个简单的形式:
<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>
Run Code Online (Sandbox Code Playgroud)
我需要在发送到服务器之前添加两个POST参数:
var params = [
{
name: "url",
value: window.location.pathname
},
{
name: "time",
value: new Date().getTime()
}
];
Run Code Online (Sandbox Code Playgroud)
请不要修改表格.
Pim*_*ger 90
要使用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;
});
Run Code Online (Sandbox Code Playgroud)
son*_*aft 21
以前的答案可以缩短,更具可读性.
$('#commentForm').submit(function () {
$(this).append($.map(params, function (param) {
return $('<input>', {
type: 'hidden',
name: param.name,
value: param.value
})
}))
});
Run Code Online (Sandbox Code Playgroud)
Mic*_*ski 14
如果要在不修改表单的情况下添加参数,则必须序列化表单,添加参数并使用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
});
Run Code Online (Sandbox Code Playgroud)
请参阅.serializeArray()和$.post()文档.
您可以在没有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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
115234 次 |
| 最近记录: |