考虑:

http://example.com/page.html?returnurl=%2Fadmin

对于page.html内的js,它如何检索GET参数?

对于上面的简单例子,func('returnurl')应该是/admin。

但它也应该适用于复杂的查询字符串…


当前回答

获取JSON对象的参数:

console.log(getUrlParameters())

function getUrlParameters() {
    var out = {};
    var str = window.location.search.replace("?", "");
    var subs = str.split(`&`).map((si)=>{var keyVal = si.split(`=`); out[keyVal[0]]=keyVal[1];});
    return out
}

其他回答

dr解决方案在一行代码上使用普通JavaScript

var queryDict = {}
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})

这是最简单的解决方案。不幸的是,它不能处理多值键和编码字符。

"?a=1&a=%2Fadmin&b=2&c=3&d&e"
> queryDict
a: "%2Fadmin"  // Overridden with the last value, not decoded.
b: "2"
c: "3"
d: undefined
e: undefined

多值键和编码字符?

请参阅如何在JavaScript中获得查询字符串值的原始答案。

"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab&a=%2Fadmin"
> queryDict
a: ["1", "5", "t e x t", "/admin"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]

在你的例子中,你可以像这样访问这个值:

"?returnurl=%2Fadmin"
> qd.returnurl    // ["/admin"]
> qd['returnurl'] // ["/admin"]
> qd.returnurl[0] // "/admin"

你应该使用URL和URLSearchParams本地函数:

let url = new url ("https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8&q=mdn%20query%20string") let params = new URLSearchParams(url.search); Let sourceid = params.get('sourceid') // 'chrome-instant' Let q = params.get('q') // 'mdn查询字符串' 让ie = params.has('ie') // true params.append(“平”、“乒乓球”) console.log (sourceid) console.log (q) console.log (ie) console.log (params.toString ()) console.log (params.get(“平”))

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams https://polyfill.io/v2/docs/features/

我创建了一个简单的JavaScript函数来从URL访问GET参数。

只要包含这个JavaScript源代码,就可以访问get参数。 例如:在http://example.com/index.php?language=french中,语言变量可以通过$_GET["language"]访问。类似地,所有参数的列表将作为数组存储在变量$_GET_Params中。JavaScript和HTML都在下面的代码片段中提供:

<!DOCTYPE html> <html> <body> <!-- This script is required --> <script> function $_GET() { // Get the Full href of the page e.g. http://www.google.com/files/script.php?v=1.8.7&country=india var href = window.location.href; // Get the protocol e.g. http var protocol = window.location.protocol + "//"; // Get the host name e.g. www.google.com var hostname = window.location.hostname; // Get the pathname e.g. /files/script.php var pathname = window.location.pathname; // Remove protocol part var queries = href.replace(protocol, ''); // Remove host part queries = queries.replace(hostname, ''); // Remove pathname part queries = queries.replace(pathname, ''); // Presently, what is left in the variable queries is : ?v=1.8.7&country=india // Perform query functions if present if (queries != "" && queries != "?") { // Remove question mark '?' queries = queries.slice(1); // Split all the different queries queries = queries.split("&"); // Get the number of queries var length = queries.length; // Declare global variables to store keys and elements $_GET_Params = new Array(); $_GET = {}; // Perform functions per query for (var i = 0; i < length; i++) { // Get the present query var key = queries[i]; // Split the query and the value key = key.split("="); // Assign value to the $_GET variable $_GET[key[0]] = [key[1]]; // Assign value to the $_GET_Params variable $_GET_Params[i] = key[0]; } } } // Execute the function $_GET(); </script> <h1>GET Parameters</h1> <h2>Try to insert some get parameter and access it through JavaScript</h2> </body> </html>

获取JSON对象的参数:

console.log(getUrlParameters())

function getUrlParameters() {
    var out = {};
    var str = window.location.search.replace("?", "");
    var subs = str.split(`&`).map((si)=>{var keyVal = si.split(`=`); out[keyVal[0]]=keyVal[1];});
    return out
}

这个函数使用正则表达式,如果参数不存在或没有任何值,则返回null:

function getQuery(q) {
   return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
}