我正在尝试预先填充一些字段,这些字段是作为参数对从URL传递的。拥有
www.example.com.com/myForm#myinput=123
作为href发送给最终用户,我将在打开链接后用"123“预填充表单域"myinput”。但是,用户还将在其浏览器中看到www.example.com.com/myForm#myInput=123。这就是为什么我要从他们的网址上删除"myInput=123“的原因。这样做的原因是,我不希望我的用户在填写表单时看到甚至更改URL中的值。
我试过了
history.pushState(null,'','/modifedURL')
HTML body中的"onload“或jquery中的"doc ready”。到目前为止,我尝试过,这只能在URL中没有任何参数的情况下独立工作,比如"www.example.com.com/myForm",但不能使用额外的注入参数。这是我到目前为止得到的代码的简化版本。注意,成功调用了modifyURL方法,但对URL没有影响:
<head>
<meta charset="utf-8" />
</head>
<body onload="prefill();">
Your Body Content
<!-- Scripts at the bottom for improved performance. -->
<!-- jQuery, required for all responsive plugins. -->
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<form id="myForm" method="POST">
<input id="myinput" maxlength="50" name="myinput" type="text" />
<br>
<input type="submit" name="submit" />
</form>
<script>
$(document).ready(function() {
//do some code after html is loaded
});
/*
window.onload = function () {
}
*/
function prefill() {
try{
var currentURL = window.location.href;
var n = currentURL.search("#");
var sPageURL = currentURL.substring(n+1);
var urlVal = getURLVal(sPageURL);
document.forms["myForm"]["myInput"].value = urlVal;
//change URL is called, but cannot change the URL!
modifyURL();
} catch(e){
alert("error " + e);
return false;
}
return true;
}
function modifyURL() {
history.pushState(null, '', '/modifedURL');
//even alert will fire, so pushState is skipped!!
alert('URL modified');
}
function getURLVal(query) {
//parse parameter pair in url
}
</script>
</body>
发布于 2018-09-15 01:51:26
你可以在你的HTML中直接包含数据,如果它总是相同的话。
有两种方法:
<input id="myinput" maxlength="50" name="myinput" type="text" value="123" />
这实际上是将值放在输入field
<input id="myinput" maxlength="50" name="myinput" type="text" placeholder="123" />
中这仅在用户插入任何实际值之前显示(在提交时,您不会获得任何值)
我希望这对你有用
https://stackoverflow.com/questions/52336853
复制相似问题