试图从数据库中获取数据,然后通过Rails中的视图
的HTML我是新到Rails和JQuery/Ajax和我试图通过JQuery的阿贾克斯发一些数据库信息,以我的观点HTMLS。在学习它的风格的过程中,我计算过,试图从数据库中获取数据,然后通过Rails中的视图
var json = {....};
$.ajax({
type: "GET",
url: '...',
data: json,
success: function (data){
//do such with data when successful
},
error: function (data){
//do such with data when failed
}
});
我试图让数据与字符串数组返回,这样我就可以把数据库中的数据自动完成JQuery的标签。我需要在控制器中做什么?例如,如果我想从用户模型中的所有用户获取user.name。
我只是想,因为当我开始使用Rails没有人帮我回答这个问题。每个人都只是说谷歌它。 所有的例子都很好,但我无法将这些东西弄清楚并连接重要的东西。
你的Rails应用程序是最有可能的RESTful应用程序。 这意味着假设你有一个products_controller.rb。如果您在命令行中键入
# all products
/products
# all products as json
/products.json
# the first product
/products/1
# call the edit page for the first product
/products/1/edit
# get the first product in json format
# we will need this in a moment
/products/1.json
:
然后,你可以像这样访问他们
rake routes
你会看到所有的相应行动。 通常你能得到类似的东西在你的routes.rb中:
resources :products
现在让我们尝试检索的第一个产品是JSON:
$(function() {
$.ajax({
url: '/products/1.json',
type: 'GET',
dataType: 'json',
complete: function (jqXHR, textStatus) {
// callback
},
success: function (data, textStatus, jqXHR) {
alert(data);
// from here on you could also get the product id
// or whatever you need
$('#someDiv').html(data); // insert the retrieved data
// into a html element.
console.log(data.name); // output the name
console.log(data.price); // output the price
},
error: function (jqXHR, textStatus, errorThrown) {
// error callback
}
});
});
你OBV。使用JQuery,因此您可以将Jquery each method添加到您的成功回调中。
还有其他的/更容易/更快的方式做到这一点,但是这会适合您的旅行给出的例子。
现在让我们尝试遍历所有产品。 请注意,网址已更改,因为现在我们需要每种可用产品。
$(function() {
$.ajax({
url: '/products.json',
type: 'GET',
dataType: 'json',
complete: function (jqXHR, textStatus) {
// callback
},
success: function (data, textStatus, jqXHR) {
alert(data);
// from here on you could also get the product id
// or whatever you need
$.each(data, function(k) {
console.log(data[k].name); // name of products
});
},
error: function (jqXHR, textStatus, errorThrown) {
// error callback
}
});
});
我必须做一个循环来获得所有的产品吗?有没有办法在控制器中操作json,所以它返回例如字符串中所有产品名称的product.name? – lostdong12 2014-11-20 22:05:37
如前所述,您可以使用JQuery每个循环遍历值。那么你可以访问像product.id,product.name等东西... – 2014-11-20 22:07:20
@ lostdong12看看我的例子我已经添加了如何访问属性。 – 2014-11-20 22:14:39
你试过问谷歌的帮助?尝试搜索“Ruby on Rails jQuery教程”。 – 2014-11-20 20:36:53
是的,这是我做的第一件事,但找不到类似的东西。 – lostdong12 2014-11-20 20:38:30
尝试像[this one]一样的搜索(https://google.com/?q=rails+ajax+action) – Coenwulf 2014-11-20 21:20:07