history模式下,获取url中的参数,并解决乱码问题

本文介绍了在history模式下如何使用encodeURIComponent和decodeURIComponent来编码和解码URL参数,以解决乱码问题。例如处理http://xxx?userId='666'&userName=’用户名‘这样的URL。同时提供了获取参数的方法,并提到了在hash模式下获取参数的参考链接,以及sessionStorageSet和sessionStorageGet方法的封装详情链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

encodeURIComponent 编码

decodeURIComponent 解码

例如:http://xxx?userId='666'&userName=’用户名‘

utils.js 

// 获取url中的参数 history模式下
export function formatUrlParams() {
  let url = window.location.href
  let obj = {}
  if (url.indexOf('?') !== -1) {
    let startIndex = url.indexOf('?') + 1
    let str;
    if(url.indexOf('#') !== -1) {
      let endIndex = url.indexOf('#')
      str = url.substring(startIndex, endIndex)
    } else {
      str = url.substring(startIndex)
    }
    let strs = str.split('&')
    for (let i = 0; i < strs.length; i++) {
      obj[strs[i].split('=')[0]] = strs[i].split('=')[1]
    }
    return obj
  }
}

获取参数 

import {formatUrlParams} from '@/utils/utils'

// 获取url上的userName
if (sessionStorageGet('userName')) {
  this.userName = sessionStorageGet('userName')
} else if (formatUrlParams() && formatUrlParams().userName) {
  this.userName = decodeURIComponent(formatUrlParams().userName)
  sessionStorageSet('userName', this.userName)
}

hash模式下,获取url中的参数,请参考链接:https://mp.youkuaiyun.com/console/editor/html/106806896

sessionStorageSet、sessionStorageGet方法封装,请参考链接:https://blog.youkuaiyun.com/qq_32678401/article/details/106807099​​​​​​​

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值