前端参数转码与解码
...大约 1 分钟
前端参数转码与解码
js参数转码
前端参数转码,将参数进行编码,防止参数被截断,导致参数丢失。
// 拼接并转码URL参数的函数
function buildQueryParams(params) {
const queryParts = [];
for (const [key, value] of Object.entries(params)) {
if (Array.isArray(value)) {
value.forEach(item => {
if (item !== undefined && item !== null) {
queryParts.push(`${encodeURIComponent(key)}=${encodeURIComponent(item)}`);
}
});
// 处理数组:方式2 - JSON.stringify后转码(适合复杂数组)
// if (value.length > 0) {
// queryParts.push(`${encodeURIComponent(key)}=${encodeURIComponent(JSON.stringify(value))}`);
// }
} else {
// 处理普通值
if (value !== undefined && value !== null) {
queryParts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
}
}
}
return queryParts.join('&');
}
// 示例用法
const params = {
name: '张三',
age: 18,
skills: ['JavaScript', 'HTML', 'CSS'],
isMarried: true
}
const queryString = buildQueryParams(params);
js参数解码
参数解码,将参数进行解码,防止参数被截断,导致参数丢失。
/**获取地址栏参数,兼容hash模式和history模式,能解析数组 */
function decodeQueryParams(queryString) {
const params = {};
// 获取当前URL的查询字符串
const url = window.location.href;
let search = '';
// history模式
if (window.location.search) {
search = window.location.search.slice(1);
} else {
// hash模式
const hashIndex = url.indexOf('#');
if (hashIndex !== -1) {
const hashPart = url.slice(hashIndex);
const queryIndex = hashPart.indexOf('?');
if (queryIndex !== -1) {
search = hashPart.slice(queryIndex + 1);
}
}
}
if (!search) return params;
search.split('&').forEach(item => {
const [key, ...valueParts] = item.split('=');
if (!key) return;
const value = valueParts.join('=');
const decodedValue = decodeURIComponent(value || '');
if (params.hasOwnProperty(key)) {
if (!Array.isArray(params[key])) {
params[key] = [params[key]];
}
params[key].push(decodedValue);
} else {
params[key] = decodedValue;
}
});
return params;
}
Powered by Waline v3.2.2