今天发现了项目的一个搜索的问题,在当前页面搜索商品,然后把输入的商品名传到另外一个页面显示查询结果。
结果发现参数貌似乱码了~
搜索的页面代码,直接把参数name通过get传参的方式带参跳转到商品列表页面
/**
* 搜索商品
*/
search() {
location.href = "/html/product_list.html?name=" + this.name;
}
在商品列表解析地址栏参数
created: function () {
// 获取地址栏请求参数字符串,最多只会接受一个参数:?categoryId=xxx或?name=xxx
let paramStrings = location.search;
// 判断是否有参数
if (paramStrings.indexOf("?") !== -1 && paramStrings.indexOf("=") !== -1) {
let params = paramStrings.split("=");
let name = params[0];
let value = params[1];
// 根据参数设置请求路径
if (name === "?name") { // 参数为商品名
this.name = value;
} else if (name === "?categoryId") { // 参数为商品分类ID
this.categoryId = value;
}
}
}
最后通过encodeURIComponent()和decodeURIComponent()方法解决了这个乱码问题~
index.js
search() {
location.href = "/html/product_list.html?name=" + encodeURIComponent(this.name);
}
product_list.js
// 获取地址栏请求参数字符串,最多只会接受一个参数:?categoryId=xxx或?name=xxx
let paramStrings = location.search;
// 判断是否有参数
if (paramStrings.indexOf("?") !== -1 && paramStrings.indexOf("=") !== -1) {
let params = paramStrings.split("=");
let name = params[0];
let value = params[1];
// 根据参数设置请求路径
if (name === "?name") { // 参数为商品名
this.name = decodeURIComponent(value);
} else if (name === "?categoryId") { // 参数为商品分类ID
this.categoryId = value;
}
}