将单个查询字符串和查询数组添加到表单中



我的网站上有一个非常简单的表单http://www.example.com

<form>
    <input type="text" value="" name="name">
</form>

我如何使我的表格看起来像这个

<form>
    <input type="text" value="tom" name="name">
</form>

如果我输入(或者用户从搜索页面转到该页面)http://www.example.com?name=tom

请记住,在某个时刻,我的形式可能是这样的。

<form>
    <input type="text" value="" name="name[]">
    <input type="text" value="" name="name[]">
    <input type="text" value="" name="name[]">
    <input type="text" value="" name="name[]">
</form>

所以我也想处理一个名称数组。我看了jQuery.param(),但不知道该怎么做。是否可以不提交给php等服务器端语言?

没有现成的jQuery方法可以从查询中获取到javascript变量的名称/值对(不过,不应该有吗?)

但是,人们已经编写了纯javascript函数来为您做到这一点:如何在javascript中获取查询字符串值?。

如果您使用Andy E对上述问题的第二个答案,您可以捕获javascript对象的所有querystring变量到名称值对。这是他写的:

var urlParams = {};
(function () {
    var match,
        pl     = /+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);
    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
})();

然后使用这些设置与jQuery的querystring名称相同名称的输入的形式值,如下所示:

$.each(urlParams, function(key, value){
    $('form [name=' + key + ']').val(value);
});

更新:由于这很难在jsFiddle中进行测试,因此这里有一个完整的网页作为工作示例。它将用url传递的值('1'、'2'和'3')替换值'a'、'b'和'c'——只需在localhost上将其设置为test.html,然后转到:http://localhost/test.html?a=1&b=2&c=3

<!DOCTYPE html>
<html><head><title>Test URL params</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" >
    $(function(){
            var urlParams = {};
            (function () {
                var match,
                pl     = /+/g,  // Regex for replacing addition symbol with a space
                search = /([^&=]+)=?([^&]*)/g,
                decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
                query  = window.location.search.substring(1);
                while (match = search.exec(query))
                   urlParams[decode(match[1])] = decode(match[2]);
            })();
            $.each(urlParams, function(key, value){
                $('form [name=' + key + ']').val(value);
            });
    });
</script>
</head>
<body>
<form>
    <input name="a" value ="a" /><input name="b" value ="a" /><input name="c" value ="a" />
</form>
</body></html>

最新更新