我见过很多jQuery示例,其中参数大小和名称都是未知的。
我的URL只会有一个字符串
http://example.com?sent=yes
我只想检测:
sent存在吗? 它等于"是"吗?
我见过很多jQuery示例,其中参数大小和名称都是未知的。
我的URL只会有一个字符串
http://example.com?sent=yes
我只想检测:
sent存在吗? 它等于"是"吗?
当前回答
这是基于Gazoris的答案,但URL解码了参数,因此当它们包含除数字和字母以外的数据时可以使用:
function urlParam(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
// Need to decode the URL parameters, including putting in a fix for the plus sign
// https://stackoverflow.com/a/24417399
return results ? decodeURIComponent(results[1].replace(/\+/g, '%20')) : null;
}
其他回答
我希望这能有所帮助。
<script type="text/javascript">
function getParameters() {
var searchString = window.location.search.substring(1),
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
return hash;
}
$(window).load(function() {
var param = getParameters();
if (typeof param.sent !== "undefined") {
// Do something.
}
});
</script>
我希望使用完整的简单REG Exp
function getQueryString1(param) {
return decodeURIComponent(
(location.search.match(RegExp("[?|&]"+param+'=(.+?)(&|$)'))||[,null])[1]
);
}
这可能有点过分了,但是现在有一个非常流行的用于解析uri的库,叫做URI.js。
例子
var uri = "http://example.org/foo.html?technology=jquery&technology=css&blog=stackoverflow"; var components = URI.parse(uri); var query = URI.parseQuery(components['query']); document.getElementById("result").innerHTML = "URI = " + uri; document.getElementById("result").innerHTML += "<br>technology = " + query['technology']; // If you look in your console, you will see that this library generates a JS array for multi-valued queries! console.log(query['technology']); console.log(query['blog']); <script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.17.0/URI.min.js"></script> <span id="result"></span>
这是基于Gazoris的答案,但URL解码了参数,因此当它们包含除数字和字母以外的数据时可以使用:
function urlParam(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
// Need to decode the URL parameters, including putting in a fix for the plus sign
// https://stackoverflow.com/a/24417399
return results ? decodeURIComponent(results[1].replace(/\+/g, '%20')) : null;
}
还有另一种功能……
function param(name) {
return (location.search.split(name + '=')[1] || '').split('&')[0];
}