背景和我的研究
我想从服务器向客户端发送数据,而无需在浏览器上重新加载页面。我正在阅读Rails guide,使用JSON似乎很有希望。 (如果我错了,请纠正我。)
2.2.8渲染JSON
JSON是许多AJAX库使用的JavaScript数据格式。轨道 内置支持将对象转换为JSON并进行渲染 JSON回到浏览器:
渲染:json => @product您不需要在对象上调用to_json 你想要渲染。如果使用:json选项,则渲染将 自动为你调用to_json。
问题
我希望能够在浏览器端渲染此JSON对象。以下是该问题的适当代码。
VideosController
class VideosController < ApplicationController
include VideosHelper
def home
@video = Video.last
end
def next
@next_video = next_video(params[:id])
render :json => @next_video
end
end
next.json.erb
{
"title": "<%= @video.title %>"
"url": "<%= @video.url %>"
"youtube_id": "<%= @video.youtube_id %>"
"genre": "<%= @video.genre %>"
"category": "<%= @video.category %>"
"likes": "<%= @video.likes %>"
"dislikes": "<%= @video.dislikes %>"
"views": "<%= @video.views %>"
"user_id": "<%= @video.user_id %>"
"created_at": "<%= @video.created_at %>"
"updated_at": "<%= @video.updated_at %>"
}
如果我想在@next_video
操作上呈现home
JSON对象。我该怎么做?
答案 0 :(得分:0)
我猜你需要一些js处理程序。在home.html.erb中有类似的东西:
$.ajax({
url: '<%= next_video_path(@video.id) %>',
type: "GET",
dataType: "json",
success: function(data) {
// something brilliant here
}
})
也可以在next.json.erb中将@video更改为@next_video(因为您没有在下一个操作中初始化@video)。还有一个建议 - 你可以使用那些重命名显示和删除主页的REST(因为你现在可以用show替换它),你需要将以前的代码更改为:
$.ajax({
url: '<%= video_path(@video.next) %>',
type: "GET",
dataType: "json",
success: function(data) {
// something brilliant here
}
})
@ video.next将返回下一个视频的ID。