views:

208

answers:

2
    var location = { "location" : {
     "name" : $("#user_loc_name").val(),
     "street_address" : $("#user_loc_street_address").val(),
     "city" : $("#user_loc_city").val(),
     "province" : $("#user_loc_province").val(),
     "country" : $("#user_loc_country").val(),
     "postal_code" : $("user_loc_postal_code").val(),
     "public" : $("#user_loc_public").attr('checked')
    }};
( ... )
$.post(url, location, success_callback);

The reason I need this 'nested' map is because I'm sending this to my rails backend, and I'm hoping I can make a simple update _ attributes(params[:location]) in the controller. Unfortunately, with this solution I get Parameters: {"location"=>"[object Object]", ...}. Not what I'm hoping for. I'm hoping for {"location"=> {"name" => "valforname", "street_address" => "valforstreetadress", ...}, ...}

If I get rid of the 'nesting' and just send the inner map it works fine, but each attribute shows up separately in the params hash and it's just cumbersome and messy. If I could get the whole map nested under a key of "location" it would be much nicer.

+1  A: 

Have a look at this:

Serializing Objects in Javascript

karim79
+1  A: 

jQuery does not support JSON serializing OOTB. Try any number of libraries. Here's the standard one:

<script src="http://www.json.org/json2.js"&gt;&lt;/script&gt;

Your code then looks like:

$.post(url, JSON.stringify(location), success_callback);
Roatin Marth
ECMA Script 3.1 makes JSON a built in global object. Firefox >= 3.5 has it, not sure about chrome, safari...Can read about it herehttps://developer.mozilla.org/En/JSON
Ryu