我只是想,因爲當我開始使用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
}
});
});
你試過問谷歌的幫助?嘗試搜索「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