我有一个带有一些GET参数的URL,如下所示:
www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
我需要得到c的全部值。我试图读取URL,但只得到m2。如何使用JavaScript执行此操作?
我有一个带有一些GET参数的URL,如下所示:
www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
我需要得到c的全部值。我试图读取URL,但只得到m2。如何使用JavaScript执行此操作?
当前回答
我使用parseUri库。它允许您完全按照您的要求进行操作:
var uri = 'www.test.com/t.html&a=1&b=3&c=m2-m3-m4-m5';
var c = uri.queryKey['c'];
// c = 'm2-m3-m4-m5'
其他回答
我尽可能喜欢速记:
网址:example.com/mortgage_calc.htm?pmts=120&intr=6.8&prin=10000
香草Javascript:
for ( var vObj = {}, i=0, vArr = window.location.search.substring(1).split('&');
i < vArr.length; v = vArr[i++].split('='), vObj[v[0]] = v[1] ){}
// vObj = {pmts: "120", intr: "6.8", prin: "10000"}
简化版,已测试
function get(name){
var r = /[?&]([^=#]+)=([^&#]*)/g,p={},match;
while(match = r.exec(window.location)) p[match[1]] = match[2];
return p[name];
}
用法:
var parameter=获取['parameter']
这是一个我觉得更可读的解决方案,但它需要一个.forEach()填充程序,用于<IE8:
var getParams = function () {
var params = {};
if (location.search) {
var parts = location.search.slice(1).split('&');
parts.forEach(function (part) {
var pair = part.split('=');
pair[0] = decodeURIComponent(pair[0]);
pair[1] = decodeURIComponent(pair[1]);
params[pair[0]] = (pair[1] !== 'undefined') ?
pair[1] : true;
});
}
return params;
}
您可以添加一个输入框,然后要求用户将值复制到其中……这非常简单:
<h1>Hey User! Can you please copy the value out of the location bar where it says like, &m=2? Thanks! And then, if you could...paste it in the box below and click the Done button?</h1>
<input type='text' id='the-url-value' />
<input type='button' value='This is the Done button. Click here after you do all that other stuff I wrote.' />
<script>
//...read the value on click
好吧,但说真的。。。我发现了这段代码,它似乎很有用:
http://www.developerdrive.com/2013/08/turning-the-querystring-into-a-json-object-using-javascript/
function queryToJSON() {
var pairs = location.search.slice(1).split('&');
var result = {};
pairs.forEach(function(pair) {
pair = pair.split('=');
result[pair[0]] = decodeURIComponent(pair[1] || '');
});
return JSON.parse(JSON.stringify(result));
}
var query = queryToJSON();
一个内衬和IE11友好:
> (window.location.href).match('c=([^&]*)')[1]
> "m2-m3-m4-m5"