没有内置的 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>