URLSearchParams()
URLSearchParams()
构造函数创建并返回一个新的 URLSearchParams
对象。
语法:
new URLSearchParams()
new URLSearchParams(options)
-new URLSearchParams([["foo", 1], ["bar", 2],]
-new URLSearchParams({ foo: 1, bar: 2 })
示例:如何使用来自一个带有查询参数(search parameter)的 URL 构建的查询参数对象创建一个新的 URL。
const url = new URL("https://example.com/?a=hello&b=world");
// url.href => https://example.com/?a=hello&b=world
const add_params= {
c: "a",
e: false.toString(),
}
const new_params = new URLSearchParams([
...Array.from(url.searchParams.entries()), // [["a","hello"],["b","world"]]
...Object.entries(add_params), // [["c","a"],["e","false"]]
]).toString()
// 或者
const new_params2 = new URLSearchParams({
...Object.fromEntries(url.searchParams), // {a: 'hello', b: 'world'}
...add_params
}).toString()
// a=hello&b=world&c=a&d=2&e=false
const new_url = new URL(`${url.origin}${url.pathname}?${new_params}`)
// https://example.com/?a=hello&b=world&c=a&d=2&e=fals
示例:window.location.search为空,url参数如何携带跳转和接收?
‘http://a.com/#/data?id=1&time=2023-06-07’通过 window.location.search 获取到的参数为空"",
这是因为使用了hash导致,因为hash会将url中第一个#后的内容都作为hash内容,所以search为空了。
可通过window.location.hash.split("?")[1]获取。
// 传入携带参数
let data = {
study_id: '123',
pageType: 'edit'
}
let url = 'http://localhost:5174/'
let params = new URLSearchParams();
for (let key in data) {
params.append(key, data[key]);
}
window.open(url + '?' + params.toString(), '_self');
// 接收参数 hash 模式
let queryString = window.location.hash.split('?')[1]; // 获取问号后面的查询字符串
let params = new URLSearchParams(queryString); // 转换为 URLSearchParams 对象
params.get('study_id'); // '123'