如何从 location.search 获取特定参数? [英] How can I get a specific parameter from location.search?
本文介绍了如何从 location.search 获取特定参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个像
http://localhost/search.php?year=2008
我将如何编写一个 JavaScript 函数来获取变量 year 并查看它是否包含任何内容?
How would I write a JavaScript function to grab the variable year and see if it contains anything?
我知道它可以通过 location.search
完成,但我不知道它是如何获取参数的.
I know it can be done with location.search
but I can’t figure out how it grabs parameters.
推荐答案
我最喜欢的获取 URL 参数的方法是这种方法:
My favorite way for getting URL params is this approach:
var parseQueryString = function() {
var str = window.location.search;
var objURL = {};
str.replace(
new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
function( $0, $1, $2, $3 ){
objURL[ $1 ] = $3;
}
);
return objURL;
};
//Example how to use it:
var params = parseQueryString();
alert(params["foo"]);
这篇关于如何从 location.search 获取特定参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文