我正在尝试将数据从一个页面传递到另一个页面。
呜呜呜.mints.com?那么=something
如何使用JavaScript阅读name
?
function parseURLParams(url) {
var queryStart = url.indexOf("?") + 1,
queryEnd = url.indexOf("#") + 1 || url.length + 1,
query = url.slice(queryStart, queryEnd - 1),
pairs = query.replace(/\+/g, " ").split("&"),
parms = {}, i, n, v, nv;
if (query === url || query === "") return;
for (i = 0; i < pairs.length; i++) {
nv = pairs[i].split("=", 2);
n = decodeURIComponent(nv[0]);
v = decodeURIComponent(nv[1]);
if (!parms.hasOwnProperty(n)) parms[n] = [];
parms[n].push(nv.length === 2 ? v : null);
}
return parms;
}
使用方法如下:
var urlString = "http://www.foo.com/bar?a=a+a&b%20b=b&c=1&c=2&d#hash";
urlParams = parseURLParams(urlString);
它返回一个像这样的对象:
{
"a" : ["a a"], /* param values are always returned as arrays */
"b b": ["b"], /* param names can have special chars as well */
"c" : ["1", "2"] /* an URL param can occur multiple times! */
"d" : [null] /* parameters without values are set to null */
}
所以
parseURLParams("www.mints.com?name=something")
给
{name: ["something"]}
编辑:original version of this answer使用基于正则表达式的URL解析方法。它使用了较短的功能,但方法存在缺陷,我用适当的解析器替换它。
我认为这也应该有效:
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
只需将其称为:
var value = $_GET('myvariable');
location.search https://developer.mozilla.org/en/DOM/window.location
虽然大多数使用某种解析例程来读取查询字符串参数。
这是一个http://safalra.com/web-design/javascript/parsing-query-strings/
这是一个解决方案。当然,这个功能不需要加载到“window.params”选项中 - 可以自定义。
window.params = function(){
var params = {};
var param_array = window.location.href.split('?')[1].split('&');
for(var i in param_array){
x = param_array[i].split('=');
params[x[0]] = x[1];
}
return params;
}();
http://www.mints.com/myurl.html?name=something&goal=true上的API调用示例:
if(window.params.name == 'something') doStuff();
else if( window.params.goal == 'true') shoutGOOOOOAAALLL();
我修复/改进了Tomalak的回答:
location.search
值而不是url。码:
function getSearchObject() {
if (location.search === "") return {};
var o = {},
nvPairs = location.search.substr(1).replace(/\+/g, " ").split("&");
nvPairs.forEach( function (pair) {
var e = pair.indexOf('=');
var n = decodeURIComponent(e < 0 ? pair : pair.substr(0,e)),
v = (e < 0 || e + 1 == pair.length)
? null :
decodeURIComponent(pair.substr(e + 1,pair.length - e));
if (!(n in o))
o[n] = v;
else if (o[n] instanceof Array)
o[n].push(v);
else
o[n] = [o[n] , v];
});
return o;
}
在我的情况下,目前选择的答案根本不起作用,我觉得这是一个相当典型的答案。我发现下面的功能here,它很棒!
function getAllUrlParams(url) {
// get query string from url (optional) or window
var queryString = url ? url.split('?')[1] : window.location.search.slice(1);
// we'll store the parameters here
var obj = {};
// if query string exists
if (queryString) {
// stuff after # is not part of query string, so get rid of it
queryString = queryString.split('#')[0];
// split our query string into its component parts
var arr = queryString.split('&');
for (var i=0; i<arr.length; i++) {
// separate the keys and the values
var a = arr[i].split('=');
// in case params look like: list[]=thing1&list[]=thing2
var paramNum = undefined;
var paramName = a[0].replace(/\[\d*\]/, function(v) {
paramNum = v.slice(1,-1);
return '';
});
// set parameter value (use 'true' if empty)
var paramValue = typeof(a[1])==='undefined' ? true : a[1];
// (optional) keep case consistent
paramName = paramName.toLowerCase();
paramValue = paramValue.toLowerCase();
// if parameter name already exists
if (obj[paramName]) {
// convert value to array (if still string)
if (typeof obj[paramName] === 'string') {
obj[paramName] = [obj[paramName]];
}
// if no array index number specified...
if (typeof paramNum === 'undefined') {
// put the value on the end of the array
obj[paramName].push(paramValue);
}
// if array index number specified...
else {
// put the value at that index number
obj[paramName][paramNum] = paramValue;
}
}
// if param name doesn't exist yet, set it
else {
obj[paramName] = paramValue;
}
}
}
return obj;
}
我也做了一个相当简单的功能。你通过以下方式调用它:get(“yourgetname”);
得到任何东西。 (现在我写了它,我注意到如果你有一个&在你的价值,它会给你%26)
function get(name){
var url = window.location.search;
var num = url.search(name);
var namel = name.length;
var frontlength = namel+num+1; //length of everything before the value
var front = url.substring(0, frontlength);
url = url.replace(front, "");
num = url.search("&");
if(num>=0) return url.substr(0,num);
if(num<0) return url;
}
它是2019年,不需要任何手写解决方案或第三方库。如果要在浏览器中解析当前页面的URL:
# running on https://www.example.com?name=n1&name=n2
let params = new URLSearchParams(location.search);
params.get('name') # => "n1"
params.getAll('name') # => ["n1", "n2"]
如果要在浏览器或Node.js中解析随机URL:
let url = 'https://www.example.com?name=n1&name=n2';
let params = (new URL(url)).searchParams;
params.get('name') # => "n1"
params.getAll('name') # => ["n1", "n2"]
它正在利用现代浏览器附带的URLSearchParams界面。