URL应该用encodeURIComponent()还是escape()编码?

时间:2013-05-09 04:28:41

标签: javascript urlencode

我正在尝试使用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('&');
};

0 个答案:

没有答案