【问题标题】:How to access json in javascript after rendering it in rails在rails中渲染后如何在javascript中访问json
【发布时间】:2012-05-18 03:10:54
【问题描述】:

如果我在 Ruby 中渲染 json,我如何访问 javascript 中的值?

在 ruby​​ 中,如果我写:

response = {:key => "val"}
response = response.to_json
render :json => response, :status => 200

如何在 javascript 中访问“val”?

如果我在 javascript 中执行 alert(response),我看到 json 周围有一个标签,这会有所不同还是预期的?

我尝试了 jQuery.parseJSON(response),但出现语法错误。如果我尝试直接访问响应,我不会得到正确的值 - 应该

response.key === "val"

评估为真?

我是在 Ruby 中错误地设置它还是在 javascript 中错误地访问它,或者两者兼而有之?

【问题讨论】:

  • 请出示javascript代码。
  • 基本上就是 if(response.key === "val") {...},但它的计算结果为 false,我不知道为什么。我认为这可能是因为
     标签,但也许这只是在使用 alert() 时发生。我主要不确定是否需要 parseJSON 或者它是否已经是 JSON。
  • ajax回调函数应该得到响应,你做了什么?
  • 在那个函数中,我做的第一件事就是 if 语句,它没有返回正确的值。

标签: javascript ruby-on-rails ruby json


【解决方案1】:

如果你能展示你的 javascript 代码,那真的很有帮助。
无论如何,一种方法是使用 jQuery 的 ajax 函数并将 dataType 设置为 json。

$.ajax({
    type: "GET",
    url: "<your link>",
    dataType: "json",
    success: function(response) {
      if (response.key)
        alert(response.key);
    });
});

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    这是一个简单的例子。

    在 ./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" %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-18
      • 1970-01-01
      相关资源
      最近更新 更多