欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 记录一下 js encodeURI和encodeURIComponent URL转码问题

记录一下 js encodeURI和encodeURIComponent URL转码问题

2025/2/26 0:02:03 来源:https://blog.csdn.net/weixin_42249565/article/details/144408998  浏览:    关键词:记录一下 js encodeURI和encodeURIComponent URL转码问题
  • escape:由于它已经被废弃,不建议在任何新的代码中使用。
  • encodeURI:当你需要对整个URI进行编码时使用,例如在将整个URL作为参数传递时。
  • encodeURIComponent:当你需要编码URI中的某一部分,尤其是查询字符串参数时使用。

记录一下js 和php 之间的 URL转码问题

直接结论

escape 不建议使用,新的js都不支持了,以前的转码功能
var encodedString = escape("Hello World!");
var decodedString = unescape(encodedString);
console.log(decodedString); // 输出: Hello World!
encodeURI 这个会保留http:// 这些,我感觉总出问题就是他的原因(这个时候跳转页面时候用)
var encodedURI = encodeURI("http://www.example.com/a b c.html?name=张三&age=20");
var decodedURI = decodeURI(encodedURI);
console.log(decodedURI); // 输出: http://www.example.com/a b c.html?name=张三&age=20
encodeURIComponent 推荐这个,最彻底,携带参数最好(这个时候当参数用)
var encodedURIComponent = encodeURIComponent("name=张三&age=20");
var decodedURIComponent = decodeURIComponent(encodedURIComponent);
console.log(decodedURIComponent); // 输出: name=张三&age=20

还有会把数据传递到后端php 解析 用 rawurldecode 函数

<?php
// 假设这是由encodeURIComponent()编码的字符串
$encodedString = "name=%E5%BC%A0%E4%B8%89&age=20";
// 使用rawurldecode()来解码
$decodedString = rawurldecode($encodedString);
// 输出解码后的字符串
echo $decodedString; // 输出: name=张三&age=20
?>

如果用php反向 对比 用 http_build_query函数,注意转换之后的对比(好像对汉字不是特别友好)

mixed http_build_query ( mixed $data [, string$numeric_prefix [, string $arg_separator [, int$enc_type = PHP_QUERY_RFC1738 ]]] )
  • $data: 你想要转换成查询字符串的数组或对象。
  • $numeric_prefix: 如果数组中有数字键,这个参数将作为数字键的前缀。
  • $arg_separator: 查询字符串中的参数分隔符,默认是&。
  • $enc_type: 指定如何编码URL。默认是PHP_QUERY_RFC1738,这会使用urlencode()来编码。如果设置为PHP_QUERY_RFC3986,则会使用rawurlencode()来编码。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词