如何在 javascript 中渲染后访问 json
How to access json in javascript after rendering it in rails
如果我在Ruby中渲染json,如何访问javascript中的值?
在红宝石中,如果我写:
response = {:key => "val"}
response = response.to_json
render :json => response, :status => 200
我将如何在javascript中访问"val"?
如果我在 javascript 中执行警报(响应(,我看到 json 周围的标签,这有什么不同还是意料之中的?
我尝试了jQuery.parseJSON(response(,但我得到了一个语法错误。如果我尝试直接访问响应,我没有得到正确的值 - 应该
response.key === "val"
评估为真?
我是否在 Ruby 中设置不正确或在 javascript 中错误地访问它,或者两者兼而有之?
如果你能展示你的javascript代码,那将非常有帮助。
无论如何,一种方法是使用 jQuery 的 ajax 函数并将 dataType 设置为 json。
$.ajax({
type: "GET",
url: "<your link>",
dataType: "json",
success: function(response) {
if (response.key)
alert(response.key);
});
});
希望这有帮助。
下面是一个简单的示例。
在 ./config/routes.rb 中
match '/index' => 'application#index'
match '/json' => 'application#json'
控制器 ./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
发出 ajax 请求的 erb 页面,在本例中为 ./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" %>
相关文章:
- 访问JSON对象内部的数组元素
- 访问json数组中的对象
- 如何访问JSON元素
- 使用Backbone.js访问JSON响应的部分
- JS/JON-通过JS访问JSON中的多个数组
- 对于循环未正确访问 JSON 对象
- 使用 jasmine-node / frisby 访问 JSON 值
- 如何访问 JSON 对象数组的第一个元素
- 如何在 for 循环中访问 json 数组字段的名称
- Javascript 不会访问 json 对象
- 无法访问JSON对象的值
- 无法访问json对象中的数据
- 访问JSON对象中的特定值
- 如何通过javascript访问JSON数据
- 从Web服务访问JSON响应
- 我可以't访问JSON中的第一个对象
- 是否有可能访问JSON对象中列出的jQuery选择器
- 为什么我可以't使用点表示法访问JSON字典元素
- 访问JSON数组时出现问题
- 如何在processing.js中访问json数据