Ajax如何检索轨控制器从红宝石数据 [英] How ajax retrieve data from ruby on rails controller
问题描述
我不熟悉的阿贾克斯也没有的Ruby on rails.I've不断自我学习做项目。
I am not familiar with ajax nor ruby on rails.I've been self learn to do project.
现在我面临的一个问题,我想用ajax从控制器获取数据。
Now I face a problem,I want to use ajax to retrieve data from controller.
我不知道怎么写的URL部分:
I'm not sure how to write the url part:
$.ajax({
type:"GET",
url:"books",
dataType:"json",
success:function(result){
alert(result);
}
})
书是我的控制器的名称(书是我的表中的一个)
books is the name of my controller(book is one of my table)
这code的作品,而是检索书籍的所有数据,我只希望它的一部分。 说,在我的书控制器动作试验的一些数据。
this code works,but instead of retrieve all data from books,I only want a part of it. say some data in action test in my books controller
def test
@test=books.find.last
respond_do |format|
format.html
format.json {render ;json=>@test}
end
end
但是当我改变URL书籍/测试,我会得到一个错误消息说,404在控制台日志中没有发现。
but when I change url to books/test,I'll get a error message say 404 not found in console log.
如何取回控制器的数据的一部分吗?在此先感谢
How can I retrieve part of controller data?thanks in advance
推荐答案
那么你的努力做的,是创建一个名为测试一个非REST风格的路线。所以,你需要添加这个到routes.rb中(见这里获取更多信息):
Well what your trying to do here is create a non RESTful route called test. So you'll need to add this into routes.rb (see here for more info):
resources :books do
collection do
get 'test'
end
end
如果你愿意,你可以通过这样的参数:
If you want, you could pass your parameters like this:
$.ajax({
type:"GET",
url:"books/test",
dataType:"json",
data: {some_parameter: 'hello'},
success:function(result){
alert(result);
}
})
然后你可以在这样的测试方法是:
Which you could then use in the test method like this:
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
这篇关于Ajax如何检索轨控制器从红宝石数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!