简体   繁体   English

通过JS AJAX调用来调用Rails控制器数据

[英]Calling Rails controller data through JS AJAX call

I'm making a rails app using this code in the controller to call an API- I initially call the inventories endpoint , then make separate calls to two other id endpoints store_id, product_id to grabs specifics pieces of data linked to the inventories. 我正在使用控制器中的此代码创建一个Rails应用程序来调用API-我最初调用inventories endpoint ,然后分别调用另外两个id端点store_id, product_id以获取链接到库存的特定数据。 This data gets passed into a hash that becomes '@inventories / transformed results': 这些数据被传递到一个散列,该散列变成“ @inventories /转换结果”:

class InventoriesController < ApplicationController
 def index
 response = Typhoeus.get("http://lcboapi.com/inventories")
 parsed_json = JSON.parse(response.body)

transformed_results = []

parsed_json["result"].each do |inventory|
  transformed_results.push(
    {
      product_name: product_lookup(inventory["product_id"]),
      store_name: store_lookup(inventory["store_id"]),
      quantity: inventory["quantity"],
    }
  )
end

@inventories = transformed_results
end
  private

  def store_lookup(store_id)
  response = Typhoeus.get("http://lcboapi.com/stores/#{store_id}")
    parsed_json = JSON.parse(response.body)
  return parsed_json["result"]["name"]
end

 def product_lookup(product_id)
 response = Typhoeus.get("http://lcboapi.com/products/#{product_id}")
     parsed_json = JSON.parse(response.body)
 return parsed_json["result"]["name"]
 end
end

My question is how best to get my json hash through AJAX into a form I can pass through and iterate in assets/javascript. 我的问题是如何最好地通过AJAX将我的json哈希值转换为一种我可以通过的形式并在Assets / javascript中进行迭代。

I am aware I can build it into the view (html.erb) and have done so, but I want to make my data interact with DOM elements. 我知道我可以将它构建到视图(html.erb)中,但是我想使我的数据与DOM元素交互。

Note: I've tried doing a simple console log to show the json data in the console as a test, with no response. 注意:我尝试做一个简单的控制台日志,以在控制台中显示json数据作为测试,但没有响应。 I'm okay with using jQuery until I get comfortable with React, but I'm not sure how to grab my @inventories data from 'assets/javascript/inventories.js' - for instance, if I wanted to grab something from a csv data bases I'd use the following, but in this case it's not quite there: 在对React感到满意之前,我可以使用jQuery,但是我不确定如何从'assets / javascript / inventories.js'中获取@inventories数据-例如,如果我想从csv中获取某些内容我将使用以下数据库,但在这种情况下,它并不存在:

document.addEventListener('DOMContentLoaded', function () {
  console.log("ready!");
  $.ajax({
url: "/inventories",
method: "GET"
 }).done(function(data){
    var products = []
    data.forEach(function(item){
      products.push(item.product_name).toString();
      console.log(products);
    });
  });

})

In one of your js files (in assets/javascript ), you'll need to do something like: 在您的一个js文件中(在assets/javascript ),您需要执行以下操作:

storeLookupResults = $.ajax({
  url: "/inventories.js",
  type: 'GET'
})
storeLookupResults.success (data) =>
  # do stuff with your results
  # 'data' will contain your json

NOTE: I made up the route, so you'll need to make sure you use a real route 注意:我已经编好了路线,所以您需要确保使用真实的路线

Then, in your InventoriesController , modify index to something like: 然后,在您的InventoriesController ,将index修改为:

def index
  response = Typhoeus.get("http://lcboapi.com/inventories")
  parsed_json = JSON.parse(response.body).with_indifferent_access

  @inventories = parsed_json[:result].map do |inventory|
    {
      product_name: product_lookup(inventory[:product_id]),
      store_name: store_lookup(inventory[:store_id]),
      quantity: inventory[:quantity],
    }
  end

  respond_to do |format|
    format.html
    format.json {render json: @inventories, status: :ok}
  end  

end

Note that .map returns an array . 请注意, .map返回一个array So, you don't have to do: 因此,您不必做:

transformed_results = []

parsed_json["result"].each do |inventory|
  transformed_results.push(
    {
      product_name: product_lookup(inventory["product_id"]),
      store_name: store_lookup(inventory["store_id"]),
      quantity: inventory["quantity"],
    }
  )
end    

@inventories = transformed_results

Also note that I did: 还要注意我做了:

parsed_json = JSON.parse(response.body).with_indifferent_access

It's a purely stylistic preference. 这是纯粹的风格偏好。 I like using symbols instead of strings. 我喜欢使用符号而不是字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM