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?
EDIT This seems to work fine if there is more than one row in the Users table.