【问题标题】:JavaScript encodeURIComponent vs PHP ulrencodeJavaScript encodeURIComponent vs PHP ulrencode
【发布时间】:2011-09-04 15:43:29
【问题描述】:

它们的区别在于PHP的urlencode+而不是%20编码空格?

对两种语言执行相同操作的函数有哪些?

【问题讨论】:

    标签: php javascript urlencode


    【解决方案1】:

    在 PHP 中使用 rawurlencode 代替 urlencode

    【讨论】:

    • 真的是这样吗? PHP 文档让我感到困惑...它说 rawurlencode 是用于 /.../ 而 urlencode 是用于 /?....
    • 这可能很有用:the-art-of-web.com/javascript/escape。它是一个在线工具,可让您查看两种语言中的每个函数如何对 URI 进行编码。 rawurlencodeencodeURIComponent 产生相同的输出。
    【解决方案2】:

    在 php 自己的文档 rawurlencode 上关注此链接

    rawurlencode 可以解决问题,链接仅供参考。

    【讨论】:

      【解决方案3】:

      实际上,即使使用 JavaScript encodeURIComponent 和 PHP rawurlencode,它们也不完全相同,例如 '(' 字符,JavaScript encodeURIComponent 不会将其转换但 PHP rawurlencode 会将其转换为 %28。经过一些实验和提示其他诸如这个问题another Stackoverflow question

      我找到了终极解决方案here

      您需要做的就是使用添加以下代码

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

      例如,它们现在将完全相同相同

      fixedEncodeURIComponent(yourUrl) (JavaScript) = (PHP) rawurlencode(yourUrl)
      

      解码没问题,JavaScript 可以使用 decodeURIComponent(),PHP 可以使用 rawurldecode

      【讨论】:

        【解决方案4】:

        我在rawurlencode()encodeURIComponent() 之间遇到了同样的问题。对我来说不同的是,直到在大量源文件中使用 encodeURIComponent() 后我才发现问题,因此返回修复并更改它们,然后重新测试所有内容不是一个选项。

        幸运的是,JS 使您能够通过为新函数分配相同的名称来“劫持”内置函数。因此,您只需对 Phantom1412 的代码稍作修改即可更改 encodeURIComponent() 的行为,而无需重新编码。

        在您的代码对encodeURIComponent() 进行任何调用之前,只需将此脚本放在您的页面中:

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

        【讨论】:

          猜你喜欢
          • 2013-09-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-10
          • 1970-01-01
          相关资源
          最近更新 更多