我需要解析查询字符串www.mysite.com/default.aspx?dest=aboutus.aspx。 如何在JavaScript中获得dest变量?
当前回答
下面是一个快速简单的JavaScript查询字符串解析方法:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
现在向page.html发起请求?x =你好:
console.log(getQueryVariable('x'));
其他回答
以下是我对@bobby发布的答案的评论,这是我将使用的代码:
function parseQuery(str)
{
if(typeof str != "string" || str.length == 0) return {};
var s = str.split("&");
var s_length = s.length;
var bit, query = {}, first, second;
for(var i = 0; i < s_length; i++)
{
bit = s[i].split("=");
first = decodeURIComponent(bit[0]);
if(first.length == 0) continue;
second = decodeURIComponent(bit[1]);
if(typeof query[first] == "undefined") query[first] = second;
else if(query[first] instanceof Array) query[first].push(second);
else query[first] = [query[first], second];
}
return query;
}
这段代码接受所提供的查询字符串(作为'str')并返回一个对象。字符串在所有&出现的情况下都被拆分,从而生成一个数组。然后遍历数组,其中的每一项都用“=”分隔。这将导致子数组,其中第0个元素是参数,第1个元素是值(如果no =符号则为undefined)。它们被映射到对象属性,例如字符串"hello=1&another=2&something"被转换为:
{
hello: "1",
another: "2",
something: undefined
}
此外,这段代码注意到重复出现,如“hello=1&hello=2”,并将结果转换为一个数组,例如:
{
hello: ["1", "2"]
}
您还会注意到它处理不使用=符号的情况。它还忽略&符号后面是否有一个等号。
对于最初的问题有点过度,但如果你需要在javascript中使用查询字符串,这是一个可重用的解决方案:)
下面是一个快速简单的JavaScript查询字符串解析方法:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
现在向page.html发起请求?x =你好:
console.log(getQueryVariable('x'));
这个怎么样?
function getQueryVar(varName){
// Grab and unescape the query string - appending an '&' keeps the RegExp simple
// for the sake of this example.
var queryStr = unescape(window.location.search) + '&';
// Dynamic replacement RegExp
var regex = new RegExp('.*?[&\\?]' + varName + '=(.*?)&.*');
// Apply RegExp to the query string
var val = queryStr.replace(regex, "$1");
// If the string is the same, we didn't find a match - return false
return val == queryStr ? false : val;
}
..然后用:
alert('Var "dest" = ' + getQueryVar('dest'));
干杯
你也可以使用Rodney Rehm的URI.js库。方法如下:-
var qs = URI('www.mysite.com/default.aspx?dest=aboutus.aspx').query(true); // == { dest : 'aboutus.aspx' }
alert(qs.dest); // == aboutus.aspx
解析当前页面的查询字符串:-
var $_GET = URI(document.URL).query(true); // ala PHP
alert($_GET['dest']); // == aboutus.aspx
我也是!http://jsfiddle.net/drzaus/8EE8k/
(注:无花哨嵌套或重复检查)
deparam = (function(d,x,params,p,i,j) {
return function (qs) {
// start bucket; can't cheat by setting it in scope declaration or it overwrites
params = {};
// remove preceding non-querystring, correct spaces, and split
qs = qs.substring(qs.indexOf('?')+1).replace(x,' ').split('&');
// march and parse
for (i = qs.length; i > 0;) {
p = qs[--i];
// allow equals in value
j = p.indexOf('=');
// what if no val?
if(j === -1) params[d(p)] = undefined;
else params[d(p.substring(0,j))] = d(p.substring(j+1));
}
return params;
};//-- fn deparam
})(decodeURIComponent, /\+/g);
和测试:
var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?third=c&fourth=d&fifth=e";
tests['just ?'] = '?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses';
tests['with equals'] = 'foo=bar&baz=quux&equals=with=extra=equals&grault=garply';
tests['no value'] = 'foo=bar&baz=&qux=quux';
tests['value omit'] = 'foo=bar&baz&qux=quux';
var $output = document.getElementById('output');
function output(msg) {
msg = Array.prototype.slice.call(arguments, 0).join("\n");
if($output) $output.innerHTML += "\n" + msg + "\n";
else console.log(msg);
}
var results = {}; // save results, so we can confirm we're not incorrectly referencing
$.each(tests, function(msg, test) {
var q = deparam(test);
results[msg] = q;
output(msg, test, JSON.stringify(q), $.param(q));
output('-------------------');
});
output('=== confirming results non-overwrite ===');
$.each(results, function(msg, result) {
output(msg, JSON.stringify(result));
output('-------------------');
});
结果:
simple params
ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
full url
http://blah.com/?third=c&fourth=d&fifth=e
{"fifth":"e","fourth":"d","third":"c"}
fifth=e&fourth=d&third=c
-------------------
just ?
?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses
{"spaces":"these are pluses","building":"Empire State Building","fruit":"apple","animal":"bear"}
spaces=these%20are%20pluses&building=Empire%20State%20Building&fruit=apple&animal=bear
-------------------
with equals
foo=bar&baz=quux&equals=with=extra=equals&grault=garply
{"grault":"garply","equals":"with=extra=equals","baz":"quux","foo":"bar"}
grault=garply&equals=with%3Dextra%3Dequals&baz=quux&foo=bar
-------------------
no value
foo=bar&baz=&qux=quux
{"qux":"quux","baz":"","foo":"bar"}
qux=quux&baz=&foo=bar
-------------------
value omit
foo=bar&baz&qux=quux
{"qux":"quux","foo":"bar"} <-- it's there, i swear!
qux=quux&baz=&foo=bar <-- ...see, jQuery found it
-------------------
推荐文章
- 检测用户何时离开网页的最佳方法?
- 当“模糊”事件发生时,我如何才能找到哪个元素的焦点去了*到*?
- React不会加载本地图像
- 如何将Blob转换为JavaScript文件
- 在另一个js文件中调用JavaScript函数
- 如何在svg元素中使用z索引?
- 如何求一个数的长度?
- 跨源请求头(CORS)与PHP头
- 如何用Express/Node以编程方式发送404响应?
- parseInt(null, 24) === 23…等等,什么?
- JavaScript变量声明在循环外还是循环内?
- 元素在“for(…in…)”循环中排序
- 在哪里放置JavaScript在HTML文件?
- 什么时候.then(success, fail)被认为是承诺的反模式?
- 转换JSON字符串到JSON对象c#