我有一个使用第三方API的 ruby on rails 网络应用程序,它提供了一些我希望使用 d3 进行可视化的数据。什么是获取数据访问权限的最佳方式?我只使用静态数据集练习d3.js。
我读了How to create d3 graph using data from Rails database,我读到了AJAX是什么,但我仍然有点迷失。如果AJAX确实是 方式,那么有人可以详细说明这个过程吗?
另外,当我这样做时,最好是使用我的网络应用程序从第三方API检索到的数据,还是应该直接从第三方API获取数据?这有什么不同吗?
答案 0 :(得分:5)
修改强>
为了更直接地回答你的问题,最好先在Rails中获得结果,然后在JavaScript中使用它们,只是为了让它更好地组织起来。
另外,在页面加载时进行AJAX调用以获取数据而不是使用Rails是(根据我的经验),异步调用在JavaScript代码尝试访问数据之前无法加载数据(如果花了太长时间)。您必须将AJAX调用设置为synchronous,以便AJAX首先返回数据,然后执行以下任何代码。如果返回了大量数据,可能会导致页面加载时间过长,这对用户体验不利。
您可能需要使用RestClient gem。
在 Gemfile :
中gem 'rest-client'
然后运行bundle install
。
然后,创建一个模型以使用您的API:
rails g model ModelForMyApi
然后运行rake db:migrate
。
在 ModelForMyApi 模型中:
class ModelForMyApi < ActiveRecord::Base
require 'rest_client'
@url
def self.getData
response = RestClient(@url, { :content_type => :json, "Api-Key" => "put your API key here" }
end
def self.retrieve_results(myParameter)
@url = "myApiUrl.com/stuff/?putYourParamNameHere=#{myParameter}"
JSON.parse(ModelForMyApi.getData)
end
end
因此,在您的控制器中,您可以执行以下操作:
class ExamplesController < ApplicationController
def index
@results = ModelForMyApi.retrieve_results("superCoolParameter")
end
end
在 index.html.erb 文件中显示结果:
<%= @results %>
这将显示整个JSON响应。如果要访问键值对中的值,请参考此示例。
假装这是你的回答:
// This is a Rails JSON object, it has arrows.
// See below for how to incorporate this in your JavaScript
{
"fruit" => "banana",
"juice" => "orange juice"
}
使用
<%= @results['fruit'] %>
在您的视图中将显示&#34; banana&#34;。这就是我如何使用Rails进行API调用。我不知道如何使用d3.js实现,但我认为最好的方法是首先从API中获取结果,然后将这些结果包含在JavaScript中。
修改强>
由于您需要将它与JavaScript一起使用,因此解析Rails中的JSON响应 可能不是最好的方法。在这种情况下,最好完全按照我上面的说明进行,但从JSON.parse()
方法中删除self.retrieve_results
函数。这将返回一个普通的JSON对象,而不是一个Rails JSON对象。
因此,在 ModelForMyApi 中,从返回行中删除JSON.parse
:
class ModelForMyApi < ActiveRecord::Base
require 'rest_client'
@url
def self.getData
response = RestClient(@url, { :content_type => :json, "Api-Key" => "put your API key here" }
end
def self.retrieve_results(myParameter)
@url = "myApiUrl.com/stuff/?putYourParamNameHere=#{myParameter}"
ModelForMyApi.getData #JSON.parse was removed
end
end
在您的JavaScript中,您所要做的就是:
var jsonObj = #{@results};
// Output to log to see all the results you can play with
console.log(jsonObj);
然后,使用上面的相同JSON示例({"fruit": "banana", "juice": "orange juice"}
),您可以在JavaScript中访问JSON,如下所示:
jsonObj.fruit // Will output "banana"
现在,您可以在d3.js代码中使用API结果。
您需要从Rails方法中删除JSON.parse
的原因是因为当您在Rails方法中使用它时,它会使您的响应如下所示:
//Javascript cannot interpret the arrows
{
"fruit" => "banana",
"juice" => "orange juice"
}
但你需要它看起来像这样:
//JavaScript likes colons. No pun intended.
{
"fruit": "banana",
"juice": "orange juice"
}