【发布时间】:2018-09-15 03:38:57
【问题描述】:
我正在尝试预填充一些从 URL 作为参数对传递的字段。有
www.example.com.com/myForm#myinput=123
作为 href 发送给最终用户,我将在打开链接后用“123”预填充表单字段“myinput”。但是,用户也会在他们的浏览器中看到 www.example.com.com/myForm#myInput=123。 这就是为什么我想从他们的 URL 中删除“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>
【问题讨论】:
-
我更好的选择是使用 base64 对您的数据进行编码,这样用户就无法轻松更改它。
-
你的建议。使用“history.pushState”单独更改 url 效果很好。但是,如果我调用我的方法“modifyURL();”在 "document.forms["myForm"]["myInput"].value = urlVal;" 之后,不会再更改 url。这就是我在苦苦挣扎的原因。