2012-08-05 56 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