How to retrieve GET parameters from javascript?
1 | http://domain.com/page.html?returnurl=%2Fadmin |
对于
对于上面的简单示例,EDCOX1〔3〕应为
但它也适用于复杂的查询字符串…
使用window.location对象。这段代码让你不需要问号。
1 | window.location.search.substr(1) |
从您的示例中,它将返回
编辑:我自由地改变了Qwerty的答案,这真的很好,正如他所指出的,我完全遵循了OP的要求:
1 2 3 4 5 6 7 8 9 10 11 12 | function findGetParameter(parameterName) { var result = null, tmp = []; location.search .substr(1) .split("&") .forEach(function (item) { tmp = item.split("="); if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]); }); return result; } |
我从他的代码中删除了重复的函数执行,将其替换为变量(tmp),还添加了
或者使用普通for循环,即使在IE8中也能工作:
1 2 3 4 5 6 7 8 9 10 | function findGetParameter(parameterName) { var result = null, tmp = []; var items = location.search.substr(1).split("&"); for (var index = 0; index < items.length; index++) { tmp = items[index].split("="); if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]); } return result; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function getSearchParameters() { var prmstr = window.location.search.substr(1); return prmstr != null && prmstr !="" ? transformToAssocArray(prmstr) : {}; } function transformToAssocArray( prmstr ) { var params = {}; var prmarr = prmstr.split("&"); for ( var i = 0; i < prmarr.length; i++) { var tmparr = prmarr[i].split("="); params[tmparr[0]] = tmparr[1]; } return params; } var params = getSearchParameters(); |
然后,通过调用
在一行代码上使用普通JavaScript的tl;dr解决方案
1 2 | var queryDict = {} location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]}) |
这是最简单的解决方案。不幸的是,它不处理多值密钥和编码字符。
1 2 3 4 5 6 7 | "?a=1&a=%2Fadmin&b=2&c=3&d&e" > queryDict a:"%2Fadmin" //overriden with last value, not decoded. b:"2" c:"3" d: undefined e: undefined |
多值密钥和编码字符?
请参阅最初的答案,了解如何在javascript中获取查询字符串值?
1 2 3 4 5 6 7 | "?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"] |
在您的示例中,您将访问这样的值:
1 2 3 4 | "?returnurl=%2Fadmin" > qd.returnurl // ["/admin"] > qd['returnurl'] // ["/admin"] > qd.returnurl[0] //"/admin" |
嘿,这是2016年的正确答案:
1 2 3 4 5 6 7 8 | some = new URLSearchParams("https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8&q=mdn%20query%20string") var q = some.get('q') // 'mdn query string' var ie = some.has('ie') // true some.append('new','here') console.log(q) console.log(ie) console.log(some) |
https://developer.mozilla.org/en-us/docs/web/api/urlsearchparamshttps://polyfill.io/v2/docs/features/功能/
一种更奇特的方法是:()
1 2 3 4 5 6 7 | var options = window.location.search.slice(1) .split('&') .reduce(function _reduce (/*Object*/ a, /*String*/ b) { b = b.split('='); a[b[0]] = decodeURIComponent(b[1]); return a; }, {}); |
我这样做(检索特定的GET参数,这里是"参数名称"):
1 | var parameterValue = decodeURIComponent(window.location.search.match(/(\?|&)parameterName\=([^&]*)/)[2]); |
在这里,我编写了这个代码来将get参数转换为一个对象,以便更容易地使用它们。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | //Get Nav Url function getNavUrl() { //Get Url return window.location.search.replace("?",""); }; function getParameters(url) { //Params obj var params = {}; //To lowercase url = url.toLowerCase(); //To array url = url.split('&'); //Iterate over url parameters array var length = url.length; for(var i=0; i<length; i++) { //Create prop var prop = url[i].slice(0, url[i].search('=')); //Create Val var value = url[i].slice(url[i].search('=')).replace('=', ''); //Params New Attr params[prop] = value; } return params; }; //Call To getParameters console.log(getParameters(getNavUrl())); |
如果参数不存在或没有值,则使用regex并返回空值:
1 2 3 | function getQuery(q) { return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1]; } |
1 2 3 4 5 6 7 8 9 | var getQueryParam = function(param) { var found; window.location.search.substr(1).split("&").forEach(function(item) { if (param == item.split("=")[0]) { found = item.split("=")[1]; } }); return found; }; |
此解决方案处理URL解码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | var params = function() { function urldecode(str) { return decodeURIComponent((str+'').replace(/\+/g, '%20')); } function transformToAssocArray( prmstr ) { var params = {}; var prmarr = prmstr.split("&"); for ( var i = 0; i < prmarr.length; i++) { var tmparr = prmarr[i].split("="); params[tmparr[0]] = urldecode(tmparr[1]); } return params; } var prmstr = window.location.search.substr(1); return prmstr != null && prmstr !="" ? transformToAssocArray(prmstr) : {}; }(); |
用途:
1 | console.log('someParam GET value is', params['someParam']); |
这里是另一个基于kat和bakudan上面的例子的例子,但是使其更通用一些。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | function getParams () { var result = {}; var tmp = []; location.search .substr (1) .split ("&") .forEach (function (item) { tmp = item.split ("="); result [tmp[0]] = decodeURIComponent (tmp[1]); }); return result; } location.getParams = getParams; console.log (location.getParams()); console.log (location.getParams()["returnurl"]); |
如果您不介意使用库而不是滚动自己的实现,请查看https://github.com/jgallen23/querystring。
我的解决方案在@ TAK3R上扩展。
当没有查询参数时,它返回空对象,并支持数组符号EDCOX1〔5〕:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function getQueryParams () { function identity (e) { return e; } function toKeyValue (params, param) { var keyValue = param.split('='); var key = keyValue[0], value = keyValue[1]; params[key] = params[key]?[value].concat(params[key]):value; return params; } return decodeURIComponent(window.location.search). replace(/^\?/, '').split('&'). filter(identity). reduce(toKeyValue, {}); } |
如果您使用的是AngularJS,则可以使用
你必须在你的应用程序中添加模块
1 | angular.module('myApp', ['ngRoute']) |
现在您可以使用服务
1 2 3 | .controller('AppCtrl', function($routeParams) { console.log($routeParams); //json object } |
要将参数作为JSON对象获取,请执行以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | alert(getUrlParameters().toSource()) function explode(delim, str) { return str.split(delim); } function getUrlParameters() { var out = {}; var str = window.location.search.replace("?",""); var subs = explode('&', str); for(var i = 0; i < subs.length; ++i) { var vals = explode('=', subs[i]); out[vals[0]] = vals[1]; } return out; } |
我创建了一个简单的javascript函数来访问从url获取参数。
只要包含这个javascript源代码,就可以访问
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | <!DOCTYPE html> <html> <body> <!-- This script is required --> 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(); GET Parameters Try to insert some get parameter and access it through javascript </body> </html> |
您可以使用位置对象中的搜索功能。搜索函数提供URL的参数部分。有关详细信息,请访问http://www.javascriptkit.com/jsref/location.shtml。
您必须解析得到的字符串以获取变量及其值,例如,在"="上拆分它们。