防止 AngularJS 路由中的 URL 编码

9

目前,当我将查询字符串传递到$location的search()方法中时,我的查询字符串被URI编码了。

示例:

$location.path('/some_path').search({'ids[]': 1})

变成

http://some_url/some_path?ids%5B%5D=1

我想知道是否有一种方法可以绕过这个问题?


1
有一个解决方法,但更重要的问题是,你应该吗?特殊字符应该在URL中进行编码。如果你不想显示它的“丑陋”,使用POST而不是GET。 - J_A_X
2
你这么做的原因是什么?即使你想出了一个好理由,也会有无数其他人反对它。无论AngularJS如何编码URL,当调用$location.search()时,它会将URL解码回到您的原始对象。在此时,您尝试做的唯一原因就是让浏览器中的URL看起来更漂亮。 - Mike Quinlan
2
@Mike 你能列举几个原因吗?谢谢!:) - Petr Peller
@PetrPeller,你现在用的方法有点绕。为什么要使用特殊字符作为“分隔符”呢?为什么不使用一个实际可行且不使用特殊字符的不同模式呢? - J_A_X
1
可能是重复的问题:AngularJS:如何避免在$location中进行URL编码 - Tony
显示剩余5条评论
1个回答

3
问题在于.search()使用了encodeUriQuery函数,该函数内部使用encodeURIComponent函数,并且this function转义了除以下字符外的所有字符:字母、十进制数字、- _ . ! ~ * ' ( )。
Angular当前源代码中的函数为source code
/**
 * This method is intended for encoding *key* or *value* parts of query component. We need a custom
 * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
 * encoded per http://tools.ietf.org/html/rfc3986:
 *    query       = *( pchar / "/" / "?" )
 *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
 *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
 *    pct-encoded   = "%" HEXDIG HEXDIG
 *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
 *                     / "*" / "+" / "," / ";" / "="
 */
function encodeUriQuery(val, pctEncodeSpaces) {
  return encodeURIComponent(val).
             replace(/%40/gi, '@').
             replace(/%3A/gi, ':').
             replace(/%24/g, '$').
             replace(/%2C/gi, ',').
             replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}

如果该函数添加了这个替换功能,那么括号将保持未编码状态:
replace(/%5B/gi, '[').
replace(/%5D/gi, ']').

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接