Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
89
rated 0 times [  92] [ 3]  / answers: 1 / hits: 15377  / 12 Years ago, wed, august 29, 2012, 12:00:00

Assuming www.mydomain.com?param1=example as an example.



What is the best way to store a second parameter that is a list of key value pairs? At the minute I use &param2=key|value,key|value. I separate the key from the value using a vertical line, and the pairing with a comma, everything after the equals is encoded using encodeURIComponent(). This works fine.



However, the user has control of the value... And as sensible human beings we all know that the first thing the user will probably do is stick a vertical bar or a comma as one of the values breaking my parameter parser. Is there a better way to do this? I've seen PHP users talking about storing associated arrays in urls but I'm looking for a pure javascript solution.


More From » jquery

 Answers
2

PHP (and other server-side languages) support passing arrays in the query string.



www.mydomain.com?param1=example&param2[key1]=value1&param2[key2]=value2


PHP will parse the GET string as such:



array(2) {
[param1]=>
string(7) example
[param2]=>
array(2) {
[key1]=>
string(6) value1
[key2]=>
string(6) value2
}
}


If you don't pass keys, it will be become a numeric array:



www.mydomain.com?param1=example&param2[]=value1&param2[]=value2


Will be parsed as:



array(2) {
[param1]=>
string(7) example
[param2]=>
array(2) {
[0]=>
string(6) value1
[1]=>
string(6) value2
}
}


UPDATE: You can also parse the query string in JavaScript.



Here is a simple jQuery plugin I made:



$.parseQuery = function(str) {
var ret = {};
$.each(str.split(&), function() {
var data = this.split('='),
name = decodeURIComponent(data.shift()),
val = decodeURIComponent(data.join(=)).replace('+', ' '),
nameVal = name.match(/(.*)[(.*)]/);

if (nameVal === null) {
ret[name] = val;
}
else {
name = nameVal[1];
nameVal = nameVal[2];
if (!ret[name]) {
ret[name] = nameVal ? {} : [];
}
if ($.isPlainObject(ret[name])) {
ret[name][nameVal] = val;
}
else if($.isArray(ret[name])){
ret[name].push(val);
}
}
});
return ret;
};


Then you can do: $.parseQuery('param1=example&param2[]=value1&param2[]=value2');.


[#83354] Tuesday, August 28, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaredsages

Total Points: 273
Total Questions: 97
Total Answers: 105

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
;