查询字符串功能失败

时间:2013-06-06 16:30:22

标签: javascript jquery query-string

我正在使用以下功能使我能够轻松地从URL中获取查询字符串。

var urlParams = {};
(function () {
var e,
    a = /\+/g,  // Regex for replacing addition symbol with a space
    r = /([^&=]+)=?([^&]*)/g,
    d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
    q = window.location.search.substring(1);

while (e = r.exec(q))
   urlParams[d(e[1])] = d(e[2]);
})();

然后我只需致电

var k=urlParams["url"];
var ttl=urlParams["title"];

除了下面的查询字符串打破了函数之外,这一直很有效:

?title=Jpreay%20will%20do%20a%20press%20release%20or%20news%20announcement%20commercial%20for%20$5,%20only%20on%20fiverr.com&cnt=For%20only%205$,%20jpreay%20will%20do%20a%20press%20release%20or%20news%20announcement%20commercial.%20Top%20Rated%20Seller%20100%%20Rating%20for%20Over%2010%20Months%20Now%20In%20this%20gig%20I%20am%20providing%20a%20news%20release%20or%20some%20other%20type%20of%20event%20|%20On%20Fiverr.com&url=http%3A%2F%2Ffiverr.com%2Fjpreay%2Ffilm-a-press-release-or-news-announcement-of-your-product-or-services

我收到以下错误:

URIError: malformed URI sequence
[Break On This Error]   
var k=urlParams["url"];

有谁能帮我弄清楚这里的问题是什么?

提前致谢!

1 个答案:

答案 0 :(得分:0)

使用unescape,并包括?在匹配的正则表达式而不是做一个子字符串。我还将空间替换移到unescape之外,以防函数不喜欢空格。

所以,我们最终得到:

var urlParams = {};
(function () {
var e,
    a = /\+/g,  // Regex for replacing addition symbol with a space
    r = /([^&?=]+)=?([^&?]*)/g,
    d = function (s) { return unescape(s).replace(a, " "); },
    q = window.location.search;

while (e = r.exec(q))
   urlParams[d(e[1])] = d(e[2]);
})();

当我测试时(使用你的字符串代替window.location.search),

var k=urlParams["url"];
var ttl=urlParams["title"];
console.log('k='+k);
console.log('ttl='+ttl);

我明白了:

k=http://fiverr.com/jpreay/film-a-press-release-or-news-announcement-of-your-product-or-services
ttl=Jpreay will do a press release or news announcement commercial for $5, only on fiverr.com
相关问题