我对 ajax 和 ruby on rails 都不熟悉。我一直在自学做项目。
现在我遇到一个问题,我想使用ajax从 Controller 中获取数据。
我不确定如何写 url 部分:
$.ajax({
type:"GET",
url:"books",
dataType:"json",
success:function(result){
alert(result);
}
})
books 是我的 Controller 的名字(book 是我的一张 table )
此代码有效,但不是从书中检索所有数据,我只想要其中的一部分。 在我的书籍 Controller 中说一些行动测试中的数据
def test
@test=books.find.last
respond_do |format|
format.html
format.json {render ;json=>@test}
end
end
但是当我将 url 更改为 books/test 时,我会收到一条错误消息,说在控制台日志中找不到 404。
如何检索部分 Controller 数据?提前致谢
最佳答案
那么您在这里尝试做的是创建一个名为 test 的非 RESTful 路由。因此,您需要将其添加到 routes.rb(有关更多信息,请参阅 here):
resources :books do
collection do
get 'test'
end
end
如果你愿意,你可以像这样传递你的参数:
$.ajax({
type:"GET",
url:"books/test",
dataType:"json",
data: {some_parameter: 'hello'},
success:function(result){
alert(result);
}
})
然后您可以像这样在测试方法中使用它:
def test
some_parameter = params[:some_parameter]
# do something with some_parameter and return the results
@test=books.find.last
respond_do |format|
format.html
format.json {render json: @test}
end
end
关于jquery - ajax 如何从 ruby on rails Controller 中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25779489/