zoukankan      html  css  js  c++  java
  • decodeURI和 decodeURIComponent以及encodeURI和encodeURIComponent的区别

    url传递参数这是很常见数据传递方式,但如果不注意也是很容易出现问题的。

    最常见的就是url传递中文乱码了以及空格被转码,而要避免这种问题出现的最佳解决方案是传递前编码,接收数据后解码。编码我们用encodeURIencodeURIComponent,解码我们用decodeURIdecodeURIComponent

    encodeURI() 把字符串编码为 URI。(对应decodeURI)
    encodeURIComponent() 把字符串编码为 URI 组件。
    decodeURI() 解码某个编码的 URI。对应encodeURI)
    decodeURIComponent() 解码一个编码的 URI 组件。(对应encodeURIComponent)

    这两种转码和解码方式具体有什么区别呢?看下面几行代码运行结果就知道了:

    var urlStr="http://www.coolfish.cn/tag/url中文乱码";  
    var enURI=encodeURI(urlStr);  
    var deURI=decodeURI(urlStr);   
    var enURIC=encodeURIComponent(urlStr);  
    var deURIC=decodeURIComponent(urlStr);
    console.log("初始URL:"+urlStr);
    console.log("encodeURI转码:"+enURI);
    console.log("decodeURI解码:"+deURI);
    console.log("encodeURIComponent转码:"+enURIC);
    console.log("decodeURIComponent解码:"+deURIC);
    

      运行结果:

    初始URL:http://www.coolfish.cn/tag/url中文乱码
    encodeURI转码:http://www.coolfish.cn/tag/url%E4%B8%AD%E6%96%87%E4%B9%B1%E7%A0%81
    decodeURI解码:http://www.coolfish.cn/tag/url中文乱码
    encodeURIComponent转码:http%3A%2F%2Fwww.coolfish.cn%2Ftag%2Furl%E4%B8%AD%E6%96%87%E4%B9%B1%E7%A0%81
    decodeURIComponent解码:http://www.coolfish.cn/tag/url中文乱码

    可以看到encodeURIComponent转码的时候会把uri进行编码(url中的://转码了)。

    当我们的url传递类似callbackURL的参数的时候,最好是使用encodeURIComponent和decodeURIComponent来编码和转码。

  • 相关阅读:
    gridcontrol中使用右健菜单popupMenu1
    无线路由信号增强办法
    sql server2008企业版和标准版
    使用apache设置绑定多个域名或网站
    VirtualBox 虚拟机复制
    Mysql 性能优化7【重要】sql语句的优化 慢查询
    Mysql 性能优化6【重要】 索引优化
    Mysql 性能优化7【重要】sql语句的优化 浅谈MySQL中优化sql语句查询常用的30种方法(转)
    mysql 高可用架构
    Mysql 复制工作原理
  • 原文地址:https://www.cnblogs.com/fixbug/p/4004400.html
Copyright © 2011-2022 走看看