对要发送到web服务器的查询字符串进行编码时-何时使用escape(),何时使用encodeURI()或encodeURIComponent():

使用转义符:

escape("% +&=");

OR

使用encodeURI()/encodeURIComponent()

encodeURI("http://www.google.com?var1=value1&var2=value2");

encodeURIComponent("var1=value1&var2=value2");

当前回答

encodeURI()-escape()函数用于javascript转义,而不是HTTP。

其他回答

encodeURIComponent不编码-__!~*'(),导致以xml字符串将数据发布到php时出现问题。

例如:<xml><text x=“100”y=“150”value=“这是一个带单引号的值”/></xml>

带encodeURI的常规转义%3Cxml%3E%3Text%20x=%22100%22%20y=%22150%22%20%20value=%2它是%20a%20value%20,带有%20single%20quote%22%20/%3E%20%3C/xml%3E

您可以看到,单引号没有编码。为了解决问题,我创建了两个函数来解决项目中的问题,即编码URL:

function encodeData(s:String):String{
    return encodeURIComponent(s).replace(/\-/g, "%2D").replace(/\_/g, "%5F").replace(/\./g, "%2E").replace(/\!/g, "%21").replace(/\~/g, "%7E").replace(/\*/g, "%2A").replace(/\'/g, "%27").replace(/\(/g, "%28").replace(/\)/g, "%29");
}

对于解码URL:

function decodeData(s:String):String{
    try{
        return decodeURIComponent(s.replace(/\%2D/g, "-").replace(/\%5F/g, "_").replace(/\%2E/g, ".").replace(/\%21/g, "!").replace(/\%7E/g, "~").replace(/\%2A/g, "*").replace(/\%27/g, "'").replace(/\%28/g, "(").replace(/\%29/g, ")"));
    }catch (e:Error) {
    }
    return "";
}

我觉得这篇文章很有启发性:Javascript疯狂:查询字符串解析

当我试图解释为什么decodeURIComponent不能正确解码“+”时,我发现了这一点。以下是摘录:

String:                         "A + B"
Expected Query String Encoding: "A+%2B+B"
escape("A + B") =               "A%20+%20B"     Wrong!
encodeURI("A + B") =            "A%20+%20B"     Wrong!
encodeURIComponent("A + B") =   "A%20%2B%20B"   Acceptable, but strange

Encoded String:                 "A+%2B+B"
Expected Decoding:              "A + B"
unescape("A+%2B+B") =           "A+++B"       Wrong!
decodeURI("A+%2B+B") =          "A+++B"       Wrong!
decodeURIComponent("A+%2B+B") = "A+++B"       Wrong!

我有这个功能。。。

var escapeURIparam = function(url) {
    if (encodeURIComponent) url = encodeURIComponent(url);
    else if (encodeURI) url = encodeURI(url);
    else url = escape(url);
    url = url.replace(/\+/g, '%2B'); // Force the replacement of "+"
    return url;
};

公认的答案是好的。延伸到最后一部分:

请注意,encodeURIComponent不转义“”字符。一个普通的错误是使用它来创建html属性,例如href='MyUrl'可能会出现注射错误。如果您是从字符串,对于属性引号使用“代替”,或添加额外的编码层('可以编码为%27)。

如果您希望安全起见,也应该对百分比编码的未保留字符进行编码。

您可以使用此方法来转义它们(源代码Mozilla)

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

// fixedEncodeURIComponent("'") --> "%27"

encodeURI()和encodeURIComponent()之间的差异正好是由encodeURIComponent编码的11个字符,而不是由encodeURI编码的:

我在GoogleChrome中使用console.table轻松生成了这个表,代码如下:

var arr=[];对于(变量i=0;i<256;i++){var char=字符串.fromCharCode(i);如果(encodeURI(char)==encodeURIComponent(字符)){arr.push({字符:char,encodeURI:encodeURI(char),encodeURIComponent:encodeURIComponent(char)});}}控制台.桌子(arr);