如何在 JavaScript 中获取“ GET”请求参数?

如何从 JavaScript 中的请求获取“ GET”变量?

JQuery 或 YUI! 是否内置了这个特性?

311660 次浏览

You can parse the URL of the current page to obtain the GET parameters. The URL can be found by using location.href.

You can use the URL to acquire the GET variables. In particular, window.location.search gives everything after (and including) the '?'. You can read more about window.location here.

Update June 2021:

Today's browsers have built-in APIs for working with URLs (URL) and query strings (URLSearchParams) and these should be preferred, unless you need to support some old browsers or Opera mini (Browser support).

Original:

All data is available under

window.location.search

you have to parse the string, eg.

function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}

just call the function with GET variable name as parameter, eg.

get('foo');

this function will return the variables value or undefined if variable has no value or doesn't exist

If you already use jquery there is a jquery plugin that handles this:

http://plugins.jquery.com/project/query-object

You could use jquery.url I did like this:

var xyz = jQuery.url.param("param_in_url");

Check the source code

Updated Source: https://github.com/allmarkedup/jQuery-URL-Parser

Just to put my two cents in, if you wanted an object containing all the requests

function getRequests() {
var s1 = location.search.substring(1, location.search.length).split('&'),
r = {}, s2, i;
for (i = 0; i < s1.length; i += 1) {
s2 = s1[i].split('=');
r[decodeURIComponent(s2[0]).toLowerCase()] = decodeURIComponent(s2[1]);
}
return r;
};


var QueryString = getRequests();


//if url === "index.html?test1=t1&test2=t2&test3=t3"
console.log(QueryString["test1"]); //logs t1
console.log(QueryString["test2"]); //logs t2
console.log(QueryString["test3"]); //logs t3

Note, the key for each get param is set to lower case. So, I made a helper function. So now it's case-insensitive.

function Request(name){
return QueryString[name.toLowerCase()];
}

A map-reduce solution:

var urlParams = location.search.split(/[?&]/).slice(1).map(function(paramPair) {
return paramPair.split(/=(.+)?/).slice(0, 2);
}).reduce(function (obj, pairArray) {
obj[pairArray[0]] = pairArray[1];
return obj;
}, {});

Usage:

For url: http://example.com?one=1&two=2
console.log(urlParams.one) // 1
console.log(urlParams.two) // 2

Today I needed to get the page's request parameters into a associative array so I put together the following, with a little help from my friends. It also handles parameters without an = as true.

With an example:

// URL: http://www.example.com/test.php?abc=123&def&xyz=&something%20else


var _GET = (function() {
var _get = {};
var re = /[?&]([^=&]+)(=?)([^&]*)/g;
while (m = re.exec(location.search))
_get[decodeURIComponent(m[1])] = (m[2] == '=' ? decodeURIComponent(m[3]) : true);
return _get;
})();


console.log(_GET);
> Object {abc: "123", def: true, xyz: "", something else: true}
console.log(_GET['something else']);
> true
console.log(_GET.abc);
> 123

The function here returns the parameter by name. With tiny changes you will be able to return base url, parameter or anchor.

function getUrlParameter(name) {
var urlOld          = window.location.href.split('?');
urlOld[1]           = urlOld[1] || '';
var urlBase         = urlOld[0];
var urlQuery        = urlOld[1].split('#');
urlQuery[1]         = urlQuery[1] || '';
var parametersString = urlQuery[0].split('&');
if (parametersString.length === 1 && parametersString[0] === '') {
parametersString = [];
}
// console.log(parametersString);
var anchor          = urlQuery[1] || '';


var urlParameters = {};
jQuery.each(parametersString, function (idx, parameterString) {
paramName   = parameterString.split('=')[0];
paramValue  = parameterString.split('=')[1];
urlParameters[paramName] = paramValue;
});
return urlParameters[name];
}

try the below code, it will help you get the GET parameters from url . for more details.

 var url_string = window.location.href; // www.test.com?filename=test
var url = new URL(url_string);
var paramValue = url.searchParams.get("filename");
alert(paramValue)

Works for me in

url: http://localhost:8080/#/?access_token=111

function get(name){
const parts = window.location.href.split('?');
if (parts.length > 1) {
name = encodeURIComponent(name);
const params = parts[1].split('&');
const found = params.filter(el => (el.split('=')[0] === name) && el);
if (found.length) return decodeURIComponent(found[0].split('=')[1]);
}
}

Unlike other answers, the UrlSearchParams object can avoid using Regexes or other string manipulation and is available is most modern browsers:

var queryString = location.search
let params = new URLSearchParams(queryString)
// example of retrieving 'id' parameter
let id = parseInt(params.get("id"))
console.log(id)