encodeURI 确保特殊字符能够正确传输

在 JavaScript 中,decodeURIComponentdecodeURIencodeURI 和 encodeURIComponent 是用于编码和解码 URI(Uniform Resource Identifier)的常用函数。它们各有不同的用途和适用场景。

1. encodeURI

encodeURI 用于对整个 URI 进行编码,确保所有特殊字符都被转换为百分号编码形式。

用途
  • 编码整个 URI,包括协议、主机名、路径、查询字符串等。
示例
const uri = "http://example.com/path?query=value&another=value with spaces"; console.log(encodeURI(uri)); // 输出: http://example.com/path?query=value&another=value%20with%20spaces

2. encodeURIComponent

encodeURIComponent 用于对 URI 的各个组成部分(如查询字符串中的值)进行编码。
用途
  • 编码 URI 的各个组成部分,如查询参数的值。
示例
const value = "value with spaces"; console.log(encodeURIComponent(value)); // 输出: value%20with%20spaces

3. decodeURI

decodeURI 用于解码整个编码后的 URI。

用途
  • 解码整个编码后的 URI。
const encodedUri = "http%3A%2F%2Fexample.com%2Fpath%3Fquery%3Dvalue%26another%3Dvalue%2520with%2520spaces"; console.log(decodeURI(encodedUri)); // 输出: http://example.com/path?query=value&another=value%20with%20spaces

4. decodeURIComponent

decodeURIComponent 用于解码 URI 的各个组成部分(如查询字符串中的值)。

用途
  • 解码 URI 的各个组成部分,如查询参数的值。
示例
const encodedValue = "value%20with%20spaces"; console.log(decodeURIComponent(encodedValue)); // 输出: value with spaces

实际应用场景

假设你有一个对象需要通过 URL 查询参数传递,并且需要对其进行编码和解码。

编码对象

<template> <div> <button @click="navigateToCustomsData">Navigate</button> </div> </template> <script> export default { data() { return { obj: { key1: 'value1', key2: 'value with spaces' } }; }, methods: { navigateToCustomsData() { const encodedData = encodeURIComponent(JSON.stringify(this.obj)); const href = this.$router.resolve({ name: 'customsDataScreen', query: { data: encodedData } }).href; window.location.href = href; } } }; </script>

解析对象

<template> <div> <pre>{{ parsedObj }}</pre> </div> </template> <script> export default { data() { return { parsedObj: null }; }, created() { this.parseQueryParams(); }, methods: { parseQueryParams() { const queryParams = this.$route.query; if (queryParams.data) { const decodedData = decodeURIComponent(queryParams.data); try { this.parsedObj = JSON.parse(decodedData); } catch (error) { console.error('Error parsing JSON:', error); this.parsedObj = null; } } } } }; </script>

总结

  • encodeURI:用于编码整个 URI,保留一些特殊字符(如 -_. 和 ~)。
  • encodeURIComponent:用于编码 URI 的各个组成部分(如查询参数的值),对所有特殊字符进行编码。
  • decodeURI:用于解码整个编码后的 URI。
  • decodeURIComponent:用于解码 URI 的各个组成部分(如查询参数的值),对所有特殊字符进行解码。

在实际应用中,根据具体情况选择合适的函数进行编码和解码。对于查询参数的值,推荐使用 encodeURIComponent 和 decodeURIComponent

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱猪头的程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值