如何从 url 参数预填充 html 表单输入字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5422265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:34:01  来源:igfitidea点击:

How can I pre-populate html form input fields from url parameters?

htmlformsurlparameters

提问by Chris Knight

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:

我有一个普通的 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 解决方案,但我更愿意避免为这种单一用途而引入整个库(目前没有使用)。谢谢。

回答by Ian

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;

回答by paradox870

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.

这应该为您预先填充。

回答by Chris Sobolewski

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