我刚刚用 AJAX 测试了一些东西,我发现如果我发出警告就成功了
alert(decodeURI('%'));
或
alert(encodeURIComponent('%'));
浏览器出现以下代码错误。
$.ajax({
type: "POST",
url: "some.php",
data: "",
success: function(html){
alert(decodeURIComponent('%'));
// alert(decodeURI('%'));
}
});
如果我使用任何其他字符串,它就可以正常工作。
是我错过了什么吗?
最佳答案
最近,我的代码中的一个 decodeURIComponent
被 & 符号 %
绊倒了,谷歌搜索让我想到了这个问题。
这是我用来处理 %
的函数,它比 Ilia 的版本更短:
function decodeURIComponentSafe(s) {
if (!s) {
return s;
}
return decodeURIComponent(s.replace(/%(?![0-9][0-9a-fA-F]+)/g, '%25'));
}
它
- 如果输入为空,则返回输入值不变
- 用
%25
替换每个%
后面没有两位数(十六进制)的数字 - 返回解码后的字符串
它也适用于这里的其他示例:
decodeURIComponentSafe("%%20Visitors")//% 访客
decodeURIComponentSafe("%Directory%20Name%")//%Directory Name%
decodeURIComponentSafe("%")//%
decodeURIComponentSafe("%1")//%1
decodeURIComponentSafe("%3F")//?
关于javascript - 为什么 decodeURIComponent ('%' ) 会锁定我的浏览器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7449588/