tags:

views:

70

answers:

3

I am doing something wrong. At the end of this o is empty. I want to pass in a string such as a=3&zz=5 and do o.a and o.zz to retrieve 3 and 5. How do i generate this object?

function MakeIntoFields_sz(sz) {
    var kvLs = sz.split('&');
    var o = new Array();
    for (var kv in kvLs) {
        var kvA = kvLs[kv].split('=');
        var k = '';
        var v = '';
        if (kvA.length > 0) {
            k = kvA[0];
            if (kvA.length > 1)
                v = kvA[1];
            o[k] = v;
        }
    }
    return o;
};
+1  A: 

You could try this simple query string parser:

function ptq(q)
{
/* parse the query */
var x = q.replace(/;/g, '&').split('&'), i, name, t;
/* q changes from string version of query to object */
for (q={}, i=0; i<x.length; i++)
{
t = x[i].split('=', 2);
name = unescape(t[0]);
if (!q[name])
q[name] = [];
if (t.length > 1)
{
q[name][q[name].length] = unescape(t[1]);
}
/* next two lines are nonstandard */
else
q[name][q[name].length] = true;
}
return q;
}

function param() {
return ptq(location.search.substring(1).replace(/\+/g, ' '));
}
mcm69
A: 

In your code you should use:

for (i=0; i<kvLs.length; i++) {
  ...
}

instead of for ... in

Thevs
for (var i = 0, l = kvLs.length; i < l; i++) is even faster
Dormilich
A: 

As someone noted, my code does work. I just tested it wrong. I used invalid data from a form and refreshing a page in firefox doesnt update textareas so i kept on testing with bad data.

acidzombie24