• 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来编码和转码。

  • 相关阅读:
    scrapy.FormRequest与FormRequest.from_response 的区别
    可迭代对象和生成器
    css选择器
    xlwt写入excel时候的合并单元格
    html form提交的几种方式
    Python decorator 拦截器
    python manage.py makemigrations & migrate
    asianux4.5 环境, 本地yum源,局域网yum源的配置
    mysql基本操作
    sqlite-mysql migrate
  • 原文地址:https://www.cnblogs.com/fixbug/p/4004400.html
Copyright © 2020-2023  润新知