我有一个get请求,它检索图形显示在页面上所需的JSON。我在JQuery中这样做,但由于我使用的API,它是不可能的 - 所以我必须在rails中执行它。
我想知道这一点:如果我在页面操作中的一个单独的线程上运行get请求,那么该变量是否可以在页面加载后传递给javascript?我不确定线程中的线程是如何工作的。
这样的事情会起作用吗?
Thread.new do
url = URI.parse("http://api.steampowered.com/IDOTAMatch_570/GetMatchHistory/v001/?key=#{ENV['STEAM_WEB_API_KEY']}&account_id=#{id}&matches_requested=25&game_mode=1234516&format=json")
res = Net::HTTP::get(url)
matchlist = JSON.parse(res)
matches = []
if matchlist['result'] == 1 then
matchlist['result']['matches'].each do |match|
matches.push(GetMatchWin(match['match_id']))
end
end
def GetMatchWin(match_id, id)
match_data = matchlist["result"]["matches"].select {|m| m["match_id"] == match_id}
end
end
end
鉴于上面的代码在一个帮助文件中,然后在控制器的操作中调用它:
def index
if not session.key?(:current_user) then
redirect_to root_path
else
gon.winlossdata = GetMatchHistoryRawData(session[:current_user][:uid32])
end
end
“gon”部分只是将数据传递给javascript的宝石。