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.

  1. var objFoo = {  
  2.     foo : "foobarblee" ,  
  3.     bar : "barbleequuz" ,  
  4.     blee : "bleequuzbaaz"  
  5.     }  
  6. for ( i in objFoo ) {  
  7.     var j = objFoo[i] ;  
  8.     alert( i + ":" + j ) ;  
  9.     }  
  10.     // 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.

  1. var query_string = new Array() ;  
  2. for ( i in objFoo ) {  
  3.     var j = objFoo[i] ;  
  4.     query_string.push( i + '=' + j ) ;  
  5.     }  
  6. var url = "http://foo.bar/?" + query_string.join('&') ;  
  7. // 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.

  1. var query_string = new Array() ;  
  2. for ( h = 0 ; h < 10 ; h++ ){  
  3.     for ( i in objFoo ) {  
  4.         var j = objFoo[i] ;  
  5.         query_string.push( i + h + '=' + j ) ;  
  6.         }  
  7.     }  
  8. var url = "http://foo.bar/?" + query_string.join('&') ;  
  9. // 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.
  1. var x = { foo : "bar" , "blee" : "quuz" } ;  
  2. $.getJSON( url , x , function(response) {  
  3.     ....  
  4.     } ) ;  
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.
  1. var x = new Array() ;  
  2. x["foo"] = "bar";   
  3. x["blee"] = "quuz" ;  
  4. $.getJSON( url , x , function(response) {  
  5.     ....  
  6.     // no love for this version  
  7.     } ) ;  

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