我知道有各种库或方法可以从查询字符串中获取数据。但是,我正在尝试学习 javascript,所以决定自己编写,如下所示:
function parseQueryString() {
var qs = window.location.href.split('?')[1];
var item = qs.split('&');
var data = {};
for (var i=0; i < item.length; i++) {
key = item[i].split('=')[0];
value = item[i].split('=')[1];
data[key] = value;
}
return data;
}
Run Code Online (Sandbox Code Playgroud)
以上看起来是不是缺少什么,或者有什么不足之处?如果是这样,我该如何改进它?
您可以使用新的“ URLSearchParams” - 但请注意浏览器支持并不普遍(https://caniuse.com/#search=URLSearchParams)
var urlParams = new URLSearchParams(window.location.search);
var activeCategory, activeComponent;
// sets the active navigation if there are query paramenters in the url
if(urlParams.has('category')) {
activeCategory = urlParams.get('category');
activeComponent= urlParams.get('component');
} else {
activeCategory = null;
activeComponent= null;
}
//eg: www.myShop.com.au?category=music&component=guitar
// gives activeCategory="music" and activeComponent = "guitar"
//eg: www.myShop.com.au
// gives activeCategory = null and activeCcomponent = null
Run Code Online (Sandbox Code Playgroud)
一些建议 - 考虑使用window.location.search直接访问查询字符串。
此外,您可能希望考虑查询字符串中存在“数组”的情况(即多个值共享相同的键)。处理该问题的一种方法可能是在data您返回的对象中返回为键找到的值数组。
有关更多详细信息,请参阅此函数更新版本中的注释:
function parseQueryString() {
// Use location.search to access query string instead
const qs = window.location.search.replace('?', '');
const items = qs.split('&');
// Consider using reduce to create the data mapping
return items.reduce((data, item) => {
const [rawKey, rawValue] = item.split('=');
const key = decodeURIComponent(rawKey);
const value = decodeURIComponent(rawValue);
// Sometimes a query string can have multiple values
// for the same key, so to factor that case in, you
// could collect an array of values for the same key
if(data[key] !== undefined) {
// If the value for this key was not previously an
// array, update it
if(!Array.isArray(data[key])) {
data[key] = [ data[key] ]
}
data[key].push(value)
}
else {
data[key] = value
}
return data
}, {})
}
Run Code Online (Sandbox Code Playgroud)