2012-08-05 57 views
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是否可能?

回答

1

有没有烤入jQuery的方式来获得从querysting名称/值对JavaScript的变量(虽然,不应该有?)

但人们已经写纯JavaScript函数来为你做的:How can I get query string values in 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中测试,这里是整个网页作为一个工作示例。它将用url('1','2'和'3')代替值'a','b'和'c' - 只需将它设置为test.html on localhost并转到: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> 
+0

感谢您的帮助。你知道这个的一个有效的例子吗?我似乎无法得到它的工作,很难在小提琴中测试? – ak85 2012-08-06 11:31:18

+0

@ ak85:查看更新。 – Faust 2012-08-06 12:24:21