我知道有各种各样的库或方法可以从queryString获取数据。但是,我尝试学习javascript,因此决定编写自己的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;
}
以上内容看起来是否缺少任何内容或有任何不足之处?如果是这样,我该如何改善?
答案 0 :(得分:2)
在访问索引之前,应始终检查分割后的长度,否则,如果url没有查询字符串,则会导致异常
print
从循环内的项目中获取值时进行相同的检查
答案 1 :(得分:2)
一些建议-考虑使用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 [key, value] = item.split('=');
// 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
}, {})
}
答案 2 :(得分:1)
您可以使用新的“ 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
答案 3 :(得分:0)
这是amiuhle's solution的变体,具有改进的正则表达式,使用功能性javascript(映射,过滤器)来处理结果。像k=1&k=2&k=3
这样的重复键被解析为数组[1, 2, 3]
。 k=1=2=3
被解析为值1=2=3
// _get(key), similar to PHP $_GET[key]
// return array of values if key is repeated in query string
window._get = function(key) {
let __get_obj;
__get_obj = window.__get_obj || (function() {
// parse query string
const input = document.location.search;
let __get_obj = {};
const re = /([^?&=]+)(?:=([^&]+))?/g;
let match;
while (match = re.exec(input)) {
// empty value = true
const [k, v] = [
decodeURIComponent(match[1]),
// empty value = true
(decodeURIComponent(match[2]) || true)
];
if (k in __get_obj) {
if (Array.isArray(__get_obj[k])) {
__get_obj[k].push(v);
} else {
__get_obj[k] = [__get_obj[k], v];
}} else {
__get_obj[k] = v;
}
}
return window.__get_obj = __get_obj;
})();
if (!key) return __get_obj;
return __get_obj[key];
};
document.write(`input = ${document.location.search}<br/><br/>output:<br/>`)
// print all key-value pairs
Object.keys(_get()).forEach(key => (
document.write(`${key} = ${_get(key)}<br/>`)
));
答案 4 :(得分:0)
你可以试试URLSearchParams
// 搜索
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
//追加
const urlParams = new URLSearchParams('?foo=bar&active=false');
const myParam = urlParams.get('foo');
console.log('foo is' , myParam)
urlParams.set('foo', 'baz')
console.log(urlParams.toString());