0

我的网站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)?

4

1 回答 1

1

没有内置的 jQuery 方法可以从查询字符串到 javascript 变量中获取名称/值对(但是,不应该有吗??)

但是人们已经为您编写了纯 JavaScript 函数: 如何在 JavaScript 中获取查询字符串值?.

如果您使用Andy E对上述问题的第二个答案,您可以将所有查询字符串变量捕获为 javascript 对象的名称-值对。这是他写的:

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 的查询字符串名称相同,如下所示:

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

更新:因为这很难在 jsFiddle 中测试,所以这里有一个完整的网页作为一个工作示例。它会将值“a”、“b”和“c”替换为 url 传入的值(“1”、“2”和“3”)——只需将其设置为 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>
于 2012-08-05T12:53:34.867 回答