Cookie Notice

As far as I know, and as far as I remember, nothing in this page does anything with Cookies.

2010/07/28

The Problem With Javascript Objects / Hashes

Javascript has Objects. This is a good thing, allowing you to do useful and good things.

var objFoo = {
    foo : "foobarblee" ,
    bar : "barbleequuz" ,
    blee : "bleequuzbaaz"
    }
for ( i in objFoo ) {
    var j = objFoo[i] ;
    alert( i + ":" + j ) ;
    }
    // Yes, this is a fairly annoying example.

I'm in a position where I had been sending stuff through AJAX by using GET. I blew out the top of what you can send by GET and now must learn to use POST.

GET is easy.

var query_string = new Array() ;
for ( i in objFoo ) {
    var j = objFoo[i] ;
    query_string.push( i + '=' + j ) ;
    }
var url = "http://foo.bar/?" + query_string.join('&') ;
// coded but not tested

That's fine, if you want to generate only the right side. For query strings, I can do this and it works.

var query_string = new Array() ;
for ( h = 0 ; h < 10 ; h++ ){
    for ( i in objFoo ) {
        var j = objFoo[i] ;
        query_string.push( i + h + '=' + j ) ;
        }
    }
var url = "http://foo.bar/?" + query_string.join('&') ;
// coded but not tested
And I do a LOT of this. Enough to get the rare 414 HTTP error code. But I cannot figure out how to do this for POST.
var x = { foo : "bar" , "blee" : "quuz" } ;
$.getJSON( url , x , function(response) {
    ....
    } ) ;
Notice that foo is just as acceptable for a value name as "blee". Quotes are optional, which means the name cannot be set via program by any means I can name. And I so far cannot fake it with Arrays being Associative/Hashes.
var x = new Array() ;
x["foo"] = "bar"; 
x["blee"] = "quuz" ;
$.getJSON( url , x , function(response) {
    ....
    // no love for this version
    } ) ;

There has to be a way around this. This is obvious enough that someone besides me hit it. Help me find the solution?

No comments:

Post a Comment