我正在尝试将数据从一个页面传递到另一个页面。
www.mints.com?name=something
如何使用JavaScript阅读name
?
答案 0 :(得分:56)
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使用基于正则表达式的网址解析方法。它使用了较短的函数,但方法存在缺陷,我用适当的解析器替换它。
答案 1 :(得分:6)
我认为这也应该有效:
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');
答案 2 :(得分:3)
location.search https://developer.mozilla.org/en/DOM/window.location
尽管大多数人使用某种解析例程来读取查询字符串参数。
这是一个http://safalra.com/web-design/javascript/parsing-query-strings/
答案 3 :(得分:3)
这是一个解决方案。当然,这个功能不需要加载到“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();
答案 4 :(得分:2)
现在是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"]
如果要解析随机URL,请在浏览器或Node.js中:
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界面。
答案 5 :(得分:1)
我修复/改进了Tomalak的回答:
location.search
值而不是网址。代码:
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;
}
答案 6 :(得分:1)
在我的案例中,目前选择的答案根本不起作用,我觉得这是一个相当典型的答案。我找到了下面的函数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;
}
答案 7 :(得分:1)
您可以轻松地做到这一点
const shopId = new URLSearchParams(window.location.search).get('shop_id');
console.log(shopId);
答案 8 :(得分:0)
我也做了一个相当简单的功能。 你打电话给: 得到(&#34; yourgetname&#34);
得到任何东西。 (现在我写了它,我注意到如果你有一个&amp;在你的价值中它会给你%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;
}
答案 9 :(得分:0)
尝试这种方式
var url_string = window.location;
var url = new URL(url_string);
var name = url.searchParams.get("name");
var tvid = url.searchParams.get("id");
答案 10 :(得分:0)
尝试这样。 例如: www.example.com?id=1
$.urlParam = function (name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
console.log($.urlParam('id'));
希望有帮助。 :)
答案 11 :(得分:0)
您可以这样做
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;
}
//enter code here
var urlString = "http://www.examle.com/bar?a=a+a&b%20b=b&c=1&c=2&d#hash";
urlParams = parseURLParams(urlString);
console.log(urlParams)