从“GET"获取值参数 (JavaScript)
我有一个带有一些 GET 参数的 URL,如下所示:
I have a URL with some GET parameters as follows:
www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
我需要获取 c
的全部值.我试图读取 URL,但我只有 m2
.如何使用 JavaScript 执行此操作?
I need to get the whole value of c
. I tried to read the URL, but I got only m2
. How do I do this using JavaScript?
JavaScript 本身 没有内置用于处理查询字符串参数的内容.
JavaScript itself has nothing built in for handling query string parameters.
在(现代)浏览器中运行的代码,您可以使用 URL
对象(浏览器提供给JS的API的一部分):
Code running in a (modern) browser you can use the URL
object (which is part of the APIs provided by browsers to JS):
var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);
对于旧版浏览器(包括 Internet Explorer),您可以使用这个 polyfill 或此答案的原始版本中的代码早于 URL
:
For older browsers (including Internet Explorer), you can use this polyfill or the code from the original version of this answer that predates URL
:
你可以访问 location.search
,它会给你从 ?
字符到 URL 的结尾或片段标识符 (#foo) 的开头,以先到者为准.
You could access location.search
, which would give you from the ?
character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.
然后你可以用这个来解析它:
Then you can parse it with this:
function parse_query_string(query) {
var vars = query.split("&");
var query_string = {};
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
var key = decodeURIComponent(pair[0]);
var value = decodeURIComponent(pair[1]);
// If first entry with this name
if (typeof query_string[key] === "undefined") {
query_string[key] = decodeURIComponent(value);
// If second entry with this name
} else if (typeof query_string[key] === "string") {
var arr = [query_string[key], decodeURIComponent(value)];
query_string[key] = arr;
// If third or later entry with this name
} else {
query_string[key].push(decodeURIComponent(value));
}
}
return query_string;
}
var query_string = "a=1&b=3&c=m2-m3-m4-m5";
var parsed_qs = parse_query_string(query_string);
console.log(parsed_qs.c);
您可以通过以下方式从当前页面的 URL 中获取查询字符串:
You can get the query string from the URL of the current page with:
var query = window.location.search.substring(1);
var qs = parse_query_string(query);