【发布时间】:2020-06-24 00:56:16
【问题描述】:
我在 JavaScript 函数中有一个常量,它需要从 Rails 控制器或直接从 JSON 端点获取值。
这是返回我需要的值的控制器操作:
class EventsController < ApplicationController
def calendar
client = Signet::OAuth2::Client.new(client_options)
client.update!(session[:authorization])
service = Google::Apis::CalendarV3::CalendarService.new
service.authorization = client
@calendar_list = service.list_calendar_lists.items
rescue Google::Apis::AuthorizationError
response = client.refresh!
session[:authorization] = session[:authorization].merge(response)
retry
end
这个控制器动作也有一个对应的 JSON 端点,localhost:3000/calendar.json:
这个 JavaScript 在我的 application.rb 文件中。我尝试将我的calendarList 常量传递给实例变量@calendar_list,但这没有用。
function getEventSources(){
const calendarList = <%= @calendar_list %>
const keyArray = calendarList.map(cal => {
return 'googleCalendarId'
})
const calendarIds = calendarList.map(cal => {
return cal["id"]
})
eventSources = []
for(i=0; i < keyArray.length; i++) {
var obj = {}
obj[keyArray[i]] = calendarIds[i]
eventSources.push(obj);
}
return eventSources
};
这是我的/calendar.json 端点:
[
{
id: "en.usa#holiday@group.v.calendar.google.com",
summary: "Holidays in United States"
},
{
id: "nba_1_%41tlanta+%48awks#sports@group.v.calendar.google.com",
summary: "Atlanta Hawks"
}
]
我需要进行某种类型的 AJAX 调用来检索此值还是有更简单的方法?
【问题讨论】:
-
calendar_list的数据类型是什么?您也许可以使用const calendarList = JSON.parse("<%= @calendar_list.to_json %>"),但是是的,使用 JSON API 端点获取数据是首选方法 -
calendar_list是Google::Apis::CalendarV3::CalendarListEntry的数组 ...我有一个用于此端点的 calendar.json.jsbuilder 文件,它返回我的 getEventSources 函数所需的确切 json。 -
在评论中回答问题时,请勿在其他评论中回答。相反,编辑您的问题,将信息添加到其中,就好像新信息一直存在一样,没有附加到最后,并且绝对没有用“编辑”或“更新”类型标签进行标记。在 cmets 中回答迫使我们阅读页面中的每条评论并尝试找出它们的顺序;如果我们需要知道什么时候发生了变化,我们可以查看编辑历史记录。
标签: javascript json ruby ajax controller