ramya
ramya

Reputation: 928

how to access rendered json objects in rails

I want to access the following array @names in my java script as json format. So in my controller I have this code:

def new 
    @release = Release.new
     @names=User.select(:name).where("name LIKE 'sr%'")
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @release }
      format.json { render :json =>{ :data1 => @names} } 
    end
  end

Please let me know how to access the data1 in my view file and how to pass the value to the javascript function .

Thanks, Ramya.

Upvotes: 0

Views: 1946

Answers (2)

apneadiving
apneadiving

Reputation: 115521

If you use jQuery, you can do:

$.getJSON('users/new.json', function(data) {
  console.log(data); //you'll find your json here
});

You do :

$(document).ready(function() { 
  $(function(){ 
    $.getJSON('releases/new.json', function(data1) { 
      alert("inside getJson"); alert(data1); console.log(data1); 
    }); 
});

But you should do:

$(document).ready(function() { 
  $.getJSON('releases/new.json', function(data1) { 
    alert("inside getJson"); alert(data1); console.log(data1); 
  }); 
});

Or:

$(document).ready(function() { 
  $(function(){ 
    $.getJSON('releases/new.json', function(data1) { 
      alert("inside getJson"); alert(data1); console.log(data1);
    }); 
  })(); 
});

Upvotes: 3

davidb
davidb

Reputation: 8954

instead of http://domain/releases/1 you type http://domain/releases/1.json and you will get the data parsed as json!

Upvotes: 2

Related Questions