1

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;
};
6
  • works for me: jsbin.com/oyedo
    – Kobi
    Commented May 31, 2010 at 10:58
  • How are you testing this? If it's in a Javascript file, you're fine. But an embedded <script> element in an XHTML file may balk at the unescaped &, no?
    – jasonmp85
    Commented May 31, 2010 at 11:01
  • @jason: I think he does alert(o), which seems to be empty. If I put a breakpoint after executing this function and I delve into the array, I see the correct values. Just try alert(o.a + ", " + o.zz). Commented May 31, 2010 at 11:08
  • Yeah, I used WebKit's console.log which prints out the whole object in a nice little explorable way (like Firebug does). It also showed that this algorithm works fine as-is.
    – jasonmp85
    Commented May 31, 2010 at 11:14
  • It turns out there was a bug in firefox. It cache data between refresh (even after a post event) which completely broke my input. Making it null even after a refresh.
    – user34537
    Commented May 31, 2010 at 11:49

3 Answers 3

1

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, ' '));
}
0

In your code you should use:

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

instead of for ... in

1
  • for (var i = 0, l = kvLs.length; i < l; i++) is even faster
    – Dormilich
    Commented May 31, 2010 at 15:56
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.