[英]What is the proper way to create a JSON object in rails, and then use jQuery/Ajax to get the JSON from an action?
[英]Create Rails Proxy for JSON
我想異步查詢Foursquare API,該API當前不允許使用舊的$ .get()。 我的短期解決方案是創建一個僅獲取數據的Helper,如下所示:
def foursquare_info_for(venue_id)
res = Net::HTTP.get_response("api.foursquare.com", "/v1/venue.json?vid=#{venue_id}")
data = JSON.parse(res.body)
info = Hash.new
info["mayor_name"] = "#{data['venue']['stats']['mayor']['user']['firstname']} #{data['venue']['stats']['mayor']['user']['lastname']}"
info["mayor_photo_src"] = "#{data['venue']['stats']['mayor']['user']['photo']}"
info["checkins"] = "#{data['venue']['stats']['checkins']}"
info
end
那行得通,但是我寧願使它成為我可以在頁面加載后通過jQuery AJAX請求獲得的代理,以加快處理速度。 我很確定該幫助程序與使代理工作所需要做的事情很接近,但是我不確定我需要在哪里放置代理JSON以便能夠使用jQuery進行獲取。
我是否在使用net / http創建代理的正確軌道上?
我在哪里將代理放在一邊,以便可以使用jQuery GET訪問它?
我認為使用Net :: HTTP足以滿足要求。
我會去上課。 就像是:
class FoursquareInfo < Struct.new(:venue_id)
def info
{ :mayor_name => mayour_name, :mayor_photo_src => mayor_photo_src, :checkins => checkins }
end
def mayor_name
"#{mayor_firstname} #{mayor_lastname}"
end
def mayor_firstname
mayor["firstname"]
end
def mayor
stats["mayor"]["user"]
end
def stats
data["venue"]["stats"]
end
def data
@data ||= JSON.parse(response.body)
end
def response
Net::HTTP.get_response("api.foursquare.com", "/v1/venue.json?vid=#{venue_id}")
end
# etc...
end
從控制器:
class FoursquareInfosController < ApplicationController
def show
render :json => FoursquareInfo.new(params[:id]).info
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.