Reputation: 5402
I have an array of hashes in ruby that I render with render :json => my_arr
. However, in my view, i see it as a string, and when I iterate over it with jQuery.each it comprehends one character at a time instead of one element of the array at a time.
In my controller:
logger.debug(my_arr) # prints [{"foo1"=>"bar1”},{“foo2”=>”bar2”}]
render :json => my_arr
In my view:
function query_facebook_for_roommate(){
$.ajax({
type: "GET",
url: "send_to_my_controller",
success: function(data){
//I see data: "[{"foo1"=>"bar1”},{“foo2”=>”bar2”}]" in the chrome debugger
jQuery.each(data, display_result)
//This iterates over each character, eg: [, {, " etc. instead of each element {"foo1"=>"bar"}, {"foo2"=>"bar2"} etc.
});
}
This was working yesterday but for some reason now it's broken. I checked out previous revisions but they're broken now too. Any idea on how I should debug this?
Upvotes: 1
Views: 201
Reputation: 23943
Perhaps your return value is not being parsed as JSON. Try this:
success: function(data){
var parsed_data = $.parseJSON( data );
jQuery.each( parsed_data, display_result );
}
or try adding the dataType
option, set as "json":
$.ajax({
...
dataType: 'json'
...
});
Upvotes: 2