-
21 Sep 2007 2:09 PM #1
Rails and JSON
Rails and JSON
Hi guys,
I am trying some very basic JSON communication between my rails server and ext. I'm using the rails .to_json method and displaying the values in an ext form. Currently I have the server spitting out:
{tim1: 1, tim2: 2, tim3: 3}
I have set the url: property of my ext form, as in:
http://extjs.com/learn/Tutorial:Load...mitting_a_Form
This JSON object shows up in firebug and is displayed as above if you access the url directly. However, upon inspection, there are no values, the object length is 0, the data property is empty, and the three fields are 'undefined'.
I'm not sure what I'm doing wrong?
Any help would be much appreciated.
Tim
-
21 Sep 2007 6:11 PM #2
Post code.
-
22 Sep 2007 12:58 AM #3
Sorry, Here is my Ext code to generate the form. As you can see it should just generate, a form with one text box in it. The text box should hold the value of some of the JSON data.
Here is the Ruby code to generate the data, found at the url:Code:Ext.onReady(function(){ var timForm = new Ext.form.Form({ labelAlign: 'right', labelWidth: 175, url:'/json/jsonData/', buttonAlign: 'right' }); var tim_name = new Ext.form.TextField({ fieldLabel: 'Tim Data', name: 'tims_data', width:190 }); timForm.fieldset( {legend:'legend'}, tim_name ); tim_json_data = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url: '/json/jsonData/'}), reader: new Ext.data.JsonReader({},[ 'tim1', 'tim2', 'tim3']), remoteSort: false }); tim_json_data.on('load', function() { tim_name.setValue(tim_json_data.getAt(0).data.tim1); timForm.render('tim-div'); }) tim_json_data.load(); });
http://localhost:3007/json/jsonData/
Any help would be much appreciated.Code:def jsonData @headers["Content-Type"] = "text/plain; charset=utf-8" tim_json_data = Hash.new() tim_json_data = {:tim1 => 1, :tim2 => 2, :tim3 => 3, :tim4 => 4} render :text=>tim_json_data.to_json, :layout=> false end
Tim
-
22 Sep 2007 12:54 PM #4
Hi Tim,
I believe there are a few errors.
In the JS code, your reader should look like:
also, getAt returns a Record object, hence:Code:reader: new Ext.data.JsonReader({ root: 'text' },[ { name: 'tim1'}, {name: 'tim2'}, {name: 'tim3'}]),
and in your rails code, you should return an array, not an hash (note that you would have multiple hashes if you had multiple records, getAt(ndx) above is the index in that array):Code:tim_name.setValue(tim_json_data.getAt(0).get("tim1"));
Code:tim_json_data = [{:tim1 => 1, :tim2 => 2, :tim3 => 3, :tim4 => 4}] render :json => { :text => tim_json_data}.to_json, :layout=> false
HTH,
Thierry
-
23 Sep 2007 3:44 AM #5
Absolutely awesome work.
Thanks very much Thiery.


Reply With Quote