我正在尝试使用encodeURIComponent
方法对网址进行编码。 URL中的某些参数还包含é
,è
等特殊字符(ISO-8859-1字符集),这些字符未正确编码。
例如,é
编码为%C3%A9
而不是%E9
作为替代方案,我使用了escape
方法进行编码,它的工作正常。
但它不会对某些字符进行编码,例如+ - * / . _ @
我怀疑我是否应该使用它,大多数文章都说应该避免使用escape()
。任何人都可以告诉我如何使用encodeURIComponent
获取正确的编码,还是应该使用escape
?
CODE:有一个函数“get”,其中发送请求,encodeFormularDatas用于编码url参数。 HTML页面编码是ISO-8859-1。
this.get = function(url, answerTreatement, options) {
var request = this.newRequest();
var target = url;
if (options.parameters) {
target += "?"+this.encodeFormularDatas(options.parameters);
}
request.open("POST", target, true);
request.send(null);
}
this.encodeFormularDatas = function(values) {
var pairs = [];
var regexp = /%20/g; // encoded space
for (var name in values) {
var value = values[name];
var pair = encodeURIComponent(name).replace(regexp, "+") + '=' +
encodeURIComponent(value).replace(regexp, "+");
pairs.push(pair);
}
return pairs.join('&');
};