2013-12-14 53 views
1

我见过如何使用Javascript和jQuery解析查询字符串信息(GET变量)。有两种不同的例子在这里(我一直喜欢第二个):获取重复GET变量的查询字符串值

How can I get query string values in JavaScript?

jquery get querystring from URL

的问题是,我有两个相同的GET变量的查询字符串(它们都称为“搜索”)。当我从第一个答案运行函数时,它只返回'search'GET变量的第一个实例,第二个答案只返回最后一个'搜索'GET变量。一个例子查询字符串是:

http://www.example.com?search=this&search=that 

我做了一些搜索和有在这个线程,似乎处理这个问题的答案:

https://gist.github.com/kares/956897

但我不到底如何知道用它写的方式来实现它。我基本上正在寻找一个函数,它可以解析查询字符串并返回匹配特定GET变量的所有(如果有的话)值(在这个例子中是'search';在上面的例子中,它会返回'this'和'that' )。

感谢您的帮助!

+0

所以在你的查询字符串,你将有搜索= A&搜索= B?请明确提出问题 –

+0

确实如此。我会更新这个问题。 – MillerMedia

+0

这个插件将解析查询字符串中的重复值到数组中。 http://benalman.com/code/projects/jquery-bbq/docs/files/jquery-ba-bbq-js.html#jQuery.deparam.querystring – Greg

回答

3

这应该做的伎俩:

var params = location.search.substr(1).split('&'), 
    results = {}; 

for(var i = 0; i < params.length; i++) 
{ 
    var temp = params[i].split('='), 
     key = temp[0], 
     val = temp[1]; 

    results[key] = results[key] || []; 
    results[key].push(val); 
} 

console.log(results); // { search: ["a", "b"] } 
0

//读取页面的URL GET变量并返回它们作为关联数组。

function getUrlVars() 
{ 
    var vars = [], hash; 
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); 
    for(var i = 0; i < hashes.length; i++) 
    { 
     hash = hashes[i].split('='); 
     if(typeof vars[hash[0]]=='undefined'){ 
     vars.push(hash[0]); 
     vars[hash[0]] = [hash[1]]; 
    }else{ 
      vars[hash[0]].push(hash[1]); 
    } 
    } 
    return vars; 
} 

你可以找到演示here