Using JSON with jRails
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":"zach@zach.com"}]
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开发者_如何学Go 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.
When there are more than one row, what you are deal is a String of your object in json format, not your json object representation. Really sorry for me english, i want explaind better ...
And if @message is a null object, because there isnt any messange, the render to json dont make anything, and when you are in your JS, you will have a problem because you dont have any response which worker. You must check your @message object. Maybe you can do that:
w.json {render :json => (@message.nil?) ? 0 : @checkpoint }
then, in your callback function you must check if your data response is "0" (like string) or one object.
I can see what you have 2 problems in your code.
It is better if you use $.getJSON to do a JSON request.
- jQuery is yet a parser of JSON... then in your callback function you only must do:
$(data).each(function(i, user){ // what you like do with a user });
- In your rails response there a error, is not a w.json { render :json => @message.to_json }, is only w.json { render :json => @message }. Whiout ".to_json".
Hope that helps.
精彩评论