If I render json in Ruby, how do I access the values in javascript?
In ruby, if I write:
response = {:key => "val"}
response = response.to_json
render :json => response, :status => 200
How would I access "val" in javascript?
If I do alert(response) in javascript, I see a tag surrounding the json, does this make a difference or is this expected?
I tried jQuery.parseJSON(response) but I got a syntax error. If I try to access response directly, I don't get the correct value- should
response.key === "val"
evaluate to true?
Am I setting it up incorrectly in Ruby or accessing it incorrectly in javascript, or both?
It would really help if you could show your javascript code.
Anyway, one way you can do it is to use jQuery's ajax function and set the dataType to json.
$.ajax({
type: "GET",
url: "<your link>",
dataType: "json",
success: function(response) {
if (response.key)
alert(response.key);
});
});
Hope this helps.
Here's a quick example.
In ./config/routes.rb
match '/index' => 'application#index'
match '/json' => 'application#json'
The controller, ./app/controllers/application_controller.rb:
class ApplicationController < ActionController::Base
protect_from_forgery
def index
# server side code required by index
end
def json
response = {:key => "val"}
response = response.to_json
render :json => response, :status => 200
end
end
The erb page an ajax request is made from, in this case ./app/views/application/index.html.erb:
<script type="text/javascript" charset="utf-8">
$(document).ready(
function(){
$("a#my_ajax").bind("ajax:success",
function(evt, data, status, xhr){
console.log(data.key);
console.log(data.key === "val");
}).bind("ajax:error", function(evt, data, status, xhr){
console.log("doh!")
});
});
</script>
<%= link_to "test", {:controller=>"application", :action => 'json'}, :remote=> true, :id => "my_ajax" %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.