当我在 url 键入 ?variable=value 时如何更改值?
How to change the value when I type ?variable=value at url?
情况:
- 输入值为空,类型隐藏
- 我在 url
输入 ?hiddenname=007
- 我点击按钮“提交”并导致函数调用()..
预计:
- 系统根据?hiddenname=007 at url使用function call()
将值填入input
- 之后,系统将值为007的表单发送到服务器。
当前结果:
- 系统仍然发送空值的表单。
url
localhost/index.html?hiddenname=007
index.html
<!DOCTYPE html>
<html>
<head>
<script>
function call(){
document.forms["form1"].hiddenname.value=hiddenname;
console.log("function run");
}
</script>
</head>
<body>
<form name="form1" action="end.php">
<input type="hidden" id="hiddenid" name="hiddenname" value="" />
<input type="submit" id="send" onclick="call()"/>
</form>
</body>
end.php
<?php
echo $_GET['hiddenname'];
?>
这将在 window 上从 URL 查询字符串中加载 hiddenname
的值,然后设置 hiddenid
输入的值:
window.onload = function () {
// get the search params from the window's URL
const urlParams = new URLSearchParams(window.location.search);
// get the value of 'hiddenname'
const myParam = urlParams.get('hiddenname');
// store this value in the input with id="hiddenid"
document.getElementById('hiddenid').value = myParam;
};
将 return true;
添加到 call() 函数。
在表单属性中添加 onsubmit="return call();"
。
并从提交按钮中删除 onclick 函数。
情况:
- 输入值为空,类型隐藏
- 我在 url 输入 ?hiddenname=007
- 我点击按钮“提交”并导致函数调用()..
预计:
- 系统根据?hiddenname=007 at url使用function call() 将值填入input
- 之后,系统将值为007的表单发送到服务器。
当前结果:
- 系统仍然发送空值的表单。
url
localhost/index.html?hiddenname=007
index.html
<!DOCTYPE html>
<html>
<head>
<script>
function call(){
document.forms["form1"].hiddenname.value=hiddenname;
console.log("function run");
}
</script>
</head>
<body>
<form name="form1" action="end.php">
<input type="hidden" id="hiddenid" name="hiddenname" value="" />
<input type="submit" id="send" onclick="call()"/>
</form>
</body>
end.php
<?php
echo $_GET['hiddenname'];
?>
这将在 window 上从 URL 查询字符串中加载 hiddenname
的值,然后设置 hiddenid
输入的值:
window.onload = function () {
// get the search params from the window's URL
const urlParams = new URLSearchParams(window.location.search);
// get the value of 'hiddenname'
const myParam = urlParams.get('hiddenname');
// store this value in the input with id="hiddenid"
document.getElementById('hiddenid').value = myParam;
};
将 return true;
添加到 call() 函数。
在表单属性中添加 onsubmit="return call();"
。
并从提交按钮中删除 onclick 函数。