Rails无法使用AJAX获取json数据

时间:2014-06-02 22:27:10

标签: javascript ruby-on-rails ajax json rabl

我有一个带有2个模型的rails应用程序,即security和stock_quote模型

security.rb

has_many :stock_quotes, dependent: :destroy

stock_quotes.rb

belongs_to :security, class_name: "Security", foreign_key: 'security_id'

我使用rabl创建了一个JSON API来显示证券的json及其各自的stock_quotes。格式如下:

安全/ show.html.rabl

object @security
attributes :id, :security, :security_code, :category

node(:edit_url){ |security| edit_security_url(security)}

child :stock_quotes do 
    attributes :stock_quote_id, :security_id, :yesterday, :current, :price_change, :percentage_change, :high, :low, :published_at
end

安全/ index.html.erb

collection @securities
extends "securities/show"

API已成功创建,当我访问 /securities.json 时,我按以下格式获取数据库中的数据

[

{
    "security": {
        "id": 1,
        "security": "Google",
        "security_code": null,
        "category": null,
        "stock_quotes": [
            {
                "stock_quote": {
                    "security_id": 1,
                    "yesterday": 8.6,
                    "current": 9.45,
                    "price_change": 0.85,
                    "percentage_change": 9.88,
                    "high": 9.45,
                    "low": 9.45,
                    "published_at": "2014-05-29T08:04:54.000Z"
                }
            }
        ]
    }
},
{
    "security": {
        "id": 2,
        "security": "Facebook",
        "security_code": null,
        "category": null,
        "stock_quotes": [
            {
                "stock_quote": {
                    "security_id": 2,
                    "yesterday": 30,
                    "current": 31.75,
                    "price_change": 1.75,
                    "percentage_change": 5.83,
                    "high": 31.75,
                    "low": 30.75,
                    "published_at": "2014-05-29T08:04:54.000Z"
                }
            }
        ]
    }
}

]

但是我无法处理这些数据。我甚至试图将它登录到控制台无济于事,并且它在firebug控制台上没有返回任何错误。这是我正在使用的 securities / index.html.erb 文件中的一个简单脚本将数据记录到控制台。

<div id="sec">
<script type="text/javascript">
  var url = "/securities.json";
  var stock = {};
  $.ajax({
   url: url,
   cache: false,
   dataType: 'jsonp', //will set cache to false by default
   context: stock,
   success: function(data){
    console.log(data);
   }
  });
</script>
</div>

在访问 / securities 页面并检查我的firebug控制台后,我发现已经执行了对 /securities.json 的获取请求但是我的数据不是按照我在代码中说明的那样登录到控制台。

如何让这些数据记录到控制台,因为我确信如果我能够在控制台上记录它,使用该数据绘制图表就是我想要的,这不会是个问题

0 个答案:

没有答案