NCo*_*der 6 javascript forms variables onclick submit
我有这个onclick电话:
onClick="mySubmit();
Run Code Online (Sandbox Code Playgroud)
调用此函数:
function mySubmit(){
document.getElementById("myForm").submit();
}
Run Code Online (Sandbox Code Playgroud)
然后提交此表单:
<form id="myForm" action="action.php" method="post">
Run Code Online (Sandbox Code Playgroud)
我的问题是:如何从onClick向表单发送变量以获得类似的东西<form id="myForm" action="action.php?id=**(the variable sent from the onclick goes here)**" method="post">
谢谢!
Jua*_*des 12
最简单的方法:在表单中附加隐藏字段.
<form id="myForm" action="action.php" method="post">
<input type='hidden' id= 'hiddenField' name='id' value='' />
<script>
function mySubmit() {
document.getElementById('hiddenField').value = "Whatever I want here";
document.getElementById("myForm").submit();
}
</script>
Run Code Online (Sandbox Code Playgroud)
或者使用像这样的功能
function addHiddenField(form, props) {
Object.keys(props).forEach(fieldName => {
var field = form[fieldName];
if (!field) {
field = document.createElement('input');
field.type = 'hidden';
field.name = fieldName;
form.appendChild(field);
}
field.value = props[fieldName];
});
}
document.querySelector('form').addEventListener('submit', () => {
addHiddenField(this, {
someQueryName: 'someQueryValue',
otherQueryName: 'otherVal'
});
});Run Code Online (Sandbox Code Playgroud)
<form>
Name
<input name=name />
<input type=submit />
</form>Run Code Online (Sandbox Code Playgroud)
请注意,您可以使用DevTools修改iframe的沙箱以允许其提交表单,并且您可以验证发布的URL. sandbox="... allow-forms"
将输入类型隐藏在表单中,然后提交表单
<input id="id" name="id" type="hidden" />
Run Code Online (Sandbox Code Playgroud)
在 javascript submit() 中设置隐藏字段的值
document.getElementById('id').value = **;
Run Code Online (Sandbox Code Playgroud)
但是通过设置 form method="post" id 将不是查询字符串的一部分,即 url 将保持 action.php 而不是如果你真的想要查询字符串中的 id ie url action.php?id=** 那么你需要更改表单method="get",这样隐藏字段id将自动成为url的一部分,即action.php?id=**
如果您确实需要使用 method="post" action="action.php",这是访问下一页上发布的值的方法