0

我正在使用以下函数使我能够轻松地从 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"];

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

提前致谢!

4

1 回答 1

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
于 2013-06-06T16:36:57.680 回答