Using JSON with jRails

Posted by Zachary on Stack Overflow See other posts from Stack Overflow or by Zachary
Published on 2010-03-16T05:07:30Z Indexed on 2010/03/16 5:16 UTC
Read the original article Hit count: 470

Filed under:
|
|
|
|

I am currently trying to use AJAX in my application via jRails. I am trying to return a JSON object from my controller, and then parse it in my Javascript. I am using json2.js to do the parsing.

Here is the code I currently have:

function getSomething()
{
    $.ajax({
        type: "GET",
        url: "map/testjson",
        success: function(data) {
            var myData = JSON.parse(data[0]);
            window.alert(myData.login);
        }
    });
}

and in the controller:

class Map::MapController < ApplicationController
  def index
  end

  def testjson
    @message = User.find(:all)
    ActiveRecord::Base.include_root_in_json = false
    respond_to do |w|
      w.json { render :json => @message.to_json }
    end

  end
end

The window.alert simply says 'undefined' (without tics).

However, if I change the javascript to window.alert(data) (the raw object returned by the controller) I get:

[{"salt":"aSalt","name":"", "created_at":"2010-03-15T02:34:25Z","remember_token_expires_at": null,"crypted_password":"aPassword", "updated_at":"2010-03-15T02:34:25Z","id":1,"remember_token":null, "login":"zgwrig2","email":"[email protected]"}]

This looks like an array of size 1, if I'm looking at it correctly, but I have tried just about every combination of JSON.parse on the data object that I can think of, and nothing seems to work.

Any ideas on what I'm doing wrong here?

© Stack Overflow or respective owner

Related posts about jrails

Related posts about jQuery