I have a vanilla html page which has a form in it. A requirement has come in to be able to pre-populate the form via the url. Something like:
我有一个vanilla html页面,里面有一个表单。已经要求能够通过URL预先填充表单。就像是:
http://some.site.com/somePage.html?forename=Bob&surname=Jones
I can't seem to find any simple solution to this. Can someone point me in the right direction with some javascript to accomplish this? Happy to use a javascript solution, but I'd prefer to avoid pulling in an entire library just for this single use (none are currently used). Thanks.
我似乎无法找到任何简单的解决方案。有人可以用一些javascript指向我正确的方向来完成这个吗?很高兴使用javascript解决方案,但我宁愿避免只为这一次使用而拉入整个库(目前没有使用)。谢谢。
3 个解决方案
#1
19
Use a custom query string Javascript function.
使用自定义查询字符串Javascript函数。
function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
var koko = querySt("koko");
Then assign the retrieved value to the input control; something like:
然后将检索到的值分配给输入控件;就像是:
document.getElementById('mytxt').value = koko;
#2
11
Are you using PHP? If so, that makes things much easier. Assuming your link as above, you can use:
你在用PHP吗?如果是这样,那会让事情变得更容易。假设您的链接如上,您可以使用:
<?php
$forename = $_GET['forename'];
$surname = $_GET['surname'];
?>
----------
<input id='forename' type='text' value='<?php echo $forename; ?>' >
<input id='surname' type='text' value='<?php echo $surname; ?>' >
That should pre-populate for you.
这应该预先填充你。
#3
10
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var get = getUrlVars();
//returns get['forename'] == bob; surname == jones
#1
19
Use a custom query string Javascript function.
使用自定义查询字符串Javascript函数。
function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
var koko = querySt("koko");
Then assign the retrieved value to the input control; something like:
然后将检索到的值分配给输入控件;就像是:
document.getElementById('mytxt').value = koko;
#2
11
Are you using PHP? If so, that makes things much easier. Assuming your link as above, you can use:
你在用PHP吗?如果是这样,那会让事情变得更容易。假设您的链接如上,您可以使用:
<?php
$forename = $_GET['forename'];
$surname = $_GET['surname'];
?>
----------
<input id='forename' type='text' value='<?php echo $forename; ?>' >
<input id='surname' type='text' value='<?php echo $surname; ?>' >
That should pre-populate for you.
这应该预先填充你。
#3
10
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var get = getUrlVars();
//returns get['forename'] == bob; surname == jones