在javascript中解析来自querystring的变量

时间:2013-01-17 21:02:47

标签: javascript jquery

  

可能重复:
  How can I get query string values?

我有以下查询字符串:

"active_tab=delivered&active_tab=all&active_tab=delivered&active_tab=outstanding
&active_tab=delivered&active_tab=outstanding&active_tab=all&active_tab=delivered&active_tab=outstanding&title_filter=conformance&title_filter=delivering&title_filter=packaging
&title_filter=delivering&title_filter=all&title_filter=delivering&title_filter=all&title_filter=packaging&title_filter=conformance&title_filter=packaging
&title_filter=delivering&title_filter=packaging&title_filter=ordered"

我如何解析上述查询字符串中的最终title_filter(“有序”)和active_tab(“已发送”)?此外,如果该查询字符串变量不存在,请将其设为= ""

2 个答案:

答案 0 :(得分:4)

var query = {};

var largeString = "active_tab=delivered&active_tab=all&active_tab=delivered&active_tab=outstanding&active_tab=delivered&active_tab=outstanding&active_tab=all&active_tab=delivered&active_tab=outstanding&title_filter=conformance&title_filter=delivering&title_filter=packaging&title_filter=delivering&title_filter=all&title_filter=delivering&title_filter=all&title_filter=packaging&title_filter=conformance&title_filter=packaging&title_filter=delivering&title_filter=packaging&title_filter=ordered";

largeString.split('&').forEach(function(keyValue){
    var kvp = p.split('=');
    query[kvp[0]]= kvp[1];
});

如果您需要支持数组:

largeString.split('&').forEach(function(keyValue){
    var kvp = keyValue.split('=');

    if(kvp[0] in query){
        if(typeof(query[kvp[0]] === 'string')){
            query[kvp[0]] = [query[kvp[0]]];
        }
        query[kvp[0]].push(kvp[1]);
    }else{
        query[kvp[0]] = kvp[1];
    }
});

答案 1 :(得分:0)

我修改了查询字符串以删除重复项,然后我做了:

var active_tab = window.location.search.split('active_tab=')[1].split('&')[0]
var title_filter = window.location.search.split('title_filter=')[1].split('&')[0]