如何在 javascript 中渲染后访问 json

How to access json in javascript after rendering it in rails

本文关键字:访问 json javascript      更新时间:2023-09-26

如果我在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" %>