Cri*_*tiC 10 javascript decodeuricomponent
我只是用AJAX测试一些东西,如果我发出警报,我发现成功了
alert(decodeURI('%'));
Run Code Online (Sandbox Code Playgroud)
要么
alert(encodeURIComponent('%'));
Run Code Online (Sandbox Code Playgroud)
浏览器错误输出以下代码.
$.ajax({
type: "POST",
url: "some.php",
data: "",
success: function(html){
alert(decodeURIComponent('%'));
// alert(decodeURI('%'));
}
});
Run Code Online (Sandbox Code Playgroud)
如果我使用任何其他字符串,它的工作正常.
这是我错过的东西吗?
Hei*_*cht 20
最近decodeURIComponent,我的代码中的a 被与号绊倒了%,谷歌搜索使我想到了这个问题。
这是我用来处理%比 Ilia 版本短的函数:
function decodeURIComponentSafe(s) {
if (!s) {
return s;
}
return decodeURIComponent(s.replace(/%(?![0-9][0-9a-fA-F]+)/g, '%25'));
}
Run Code Online (Sandbox Code Playgroud)
它
%两位数(十六进制)数字替换每个NOT 后跟%25它还适用于此处的其他示例:
decodeURIComponentSafe("%%20Visitors") // % VisitorsdecodeURIComponentSafe("%Directory%20Name%") // %Directory Name%decodeURIComponentSafe("%") // %decodeURIComponentSafe("%1") // %1decodeURIComponentSafe("%3F") // ?Jua*_*des 15
从控制台尝试时,Chrome barf.它给出了一个URIError:URI格式错误.%是一个转义字符,它不能单独使用.
关键在于,如果你使用单一,%它会破坏decodeURIComponent()函数的逻辑,因为它需要紧随其后的两位数据值,例如%20(空格).
周围有一个黑客.我们需要首先检查decodeURIComponent()实际上是否可以在给定的字符串上运行,如果不能按原样返回字符串.
例:
function decodeURIComponentSafe(uri, mod) {
var out = new String(),
arr,
i = 0,
l,
x;
typeof mod === "undefined" ? mod = 0 : 0;
arr = uri.split(/(%(?:d0|d1)%.{2})/);
for (l = arr.length; i < l; i++) {
try {
x = decodeURIComponent(arr[i]);
} catch (e) {
x = mod ? arr[i].replace(/%(?!\d+)/g, '%25') : arr[i];
}
out += x;
}
return out;
}
Run Code Online (Sandbox Code Playgroud)
运行:
decodeURIComponent("%Directory%20Name%")
Run Code Online (Sandbox Code Playgroud)
会导致Uncaught URIError: URI malformed错误
而:
decodeURIComponentSafe("%Directory%20Name%") // %Directory%20Name%
Run Code Online (Sandbox Code Playgroud)
将返回初始字符串.
如果您希望拥有固定/正确的URI并且已经%转换为%25必须将其1作为附加参数传递给自定义函数:
decodeURIComponentSafe("%Directory%20Name%", 1) // "%25Directory%20Name%25"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20963 次 |
| 最近记录: |