为了账号安全,请及时绑定邮箱和手机立即绑定

什么时候使用转义代替encodeURI/encodeURIComponent?

什么时候使用转义代替encodeURI/encodeURIComponent?

慕田峪4524236 2019-06-03 14:52:45
什么时候使用转义代替encodeURI/encodeURIComponent?在编码要发送到web服务器的查询字符串时-何时使用escape()你什么时候用encodeURI()或encodeURIComponent():使用转义:escape("% +&=");或使用encodeURI()/encodeURIComponent()encodeURI("http://www.google.com?var1=value1&var2=value2");encodeURIComponent("var1=value1&var2=value2");
查看完整描述

4 回答

?
12345678_0001

TA贡献1802条经验 获得超5个赞


encodeURIComponent不编码-_.!~*'(),导致在XML字符串中将数据提交给php时出现问题。


例如:

<xml><text x="100" y="150" value="It's a value with single quote" />

</xml>


一般逃逸encodeURI

%3Cxml%3E%3Ctext%20x=%22100%22%20y=%22150%22%20value=%22It's%20a%20value%20with%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 "";

}


查看完整回答
反对 回复 2019-06-03
?
HUWWW

TA贡献1874条经验 获得超12个赞

.之间的区别encodeURI()和encodeURIComponent()这11个字符是由encodeURIComponent编码的,而不是由encodeURI编码的:


https://img1.sycdn.imooc.com//5cf4c3f10001d66104830198.jpg

我很容易地生成了这个表控制台表在GoogleChrome中使用以下代码:


var arr = [];

for(var i=0;i<256;i++) {

  var char=String.fromCharCode(i);

  if(encodeURI(char)!==encodeURIComponent(char)) {

    arr.push({

      character:char,

      encodeURI:encodeURI(char),

      encodeURIComponent:encodeURIComponent(char)

    });

  }

}

console.table(arr);


查看完整回答
反对 回复 2019-06-03
  • 4 回答
  • 0 关注
  • 1408 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号