从 URL 创建一个 JavaScript 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4297765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make a JavaScript array from URL
提问by skazhy
I need to make a Javascript array from URL, eg:
我需要从 URL 创建一个 Javascript 数组,例如:
turn this:
转这个:
http://maps.google.com/maps/api/staticmap?center=Baker Street 221b, London&size=450x450&markers=Baker Street 221b, London&sensor=false
Into something like:
进入类似的东西:
array['center'] = Baker Street 221b, London
array['size'] = 450x450
// and so on...
I need to make this serializaion/unserialization work both ways (url to array and array to the part of the url). Are there some built-in functions that do this?
我需要使这个序列化/反序列化双向工作(url 到数组和数组到 url 的一部分)。是否有一些内置函数可以做到这一点?
Thanks in advance!
提前致谢!
回答by casablanca
URL to array: (adapted from my answer here)
数组的 URL:(根据我的回答改编)
function URLToArray(url) {
var request = {};
var pairs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
if(!pairs[i])
continue;
var pair = pairs[i].split('=');
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return request;
}
Array to URL:
数组到 URL:
function ArrayToURL(array) {
var pairs = [];
for (var key in array)
if (array.hasOwnProperty(key))
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(array[key]));
return pairs.join('&');
}
回答by alex toader
the above function URLToArray is not working when url string has elem[]=23&elem[]=56.. see below the adapted function... hope it is working - not 100% tested
当 url 字符串具有 elem[]=23&elem[]=56 时,上面的函数 URLToArray 不起作用..见下面的适应函数......希望它起作用 - 不是 100% 测试
function URLToArray(url) {
var request = {};
var arr = [];
var pairs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
//check we have an array here - add array numeric indexes so the key elem[] is not identical.
if(endsWith(decodeURIComponent(pair[0]), '[]') ) {
var arrName = decodeURIComponent(pair[0]).substring(0, decodeURIComponent(pair[0]).length - 2);
if(!(arrName in arr)) {
arr.push(arrName);
arr[arrName] = [];
}
arr[arrName].push(decodeURIComponent(pair[1]));
request[arrName] = arr[arrName];
} else {
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
}
return request;
}
where endWith is taken from here
endWith 取自此处
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
回答by SEN
/**
* (C)VIOLONIX inc.
* Parser for make multidim array from
* foo[]=any&foo[]=boy, or foo[0][kids]=any&foo[1][kids]=boy
* result: foo=[[any],[boy]] or foo=[kids:[any],kids:[boy]]
*/
var URLToArray = function(url){
function parse_mdim(name, val, data){
let params = name.match(/(\[\])|(\[.+?\])/g);
if(!params)params = new Array();
let tg_id = name.split('[')[0];
if(!(tg_id in data)) data[tg_id] = [];
var prev_data = data[tg_id];
for(var i=0;i<params.length;i++){
if(params[i]!='[]'){
let tparam = params[i].match(/\[(.+)\]/i)[1];
if(!(tparam in prev_data)) prev_data[tparam] = [];
prev_data = prev_data[tparam];
}else{
prev_data.push([]);
prev_data = prev_data[prev_data.length-1];
}
}
prev_data.push(val);
}
var request = {};
var arr = [];
var pairs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
if(decodeURIComponent(pair[0]).indexOf('[')!=-1)
parse_mdim(decodeURIComponent(pair[0]), decodeURIComponent(pair[1]), request);
else
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
//To-do here check array and simplifity it: if parameter end with one index in array replace it by value [0]
return request;
}
回答by Eric
There's the query-object
jQuery pluginfor that