我的网站上有一个非常简单的表单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?
答案 0 :(得分:1)
没有用jQuery方法从查询到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中很难测试,这里有一个完整的网页作为工作示例。它会将值'a','b'和'c'替换为url传递的值('1','2'和'3') - 只需将其设置为localhost 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>