2014-11-20 55 views
0

的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。

+0

你試過問谷歌的幫助?嘗試搜索「Ruby on Rails jQuery教程」。 – 2014-11-20 20:36:53

+0

是的,這是我做的第一件事,但找不到類似的東西。 – lostdong12 2014-11-20 20:38:30

+0

嘗試像[this one]一樣的搜索(https://google.com/?q=rails+ajax+action) – Coenwulf 2014-11-20 21:20:07

回答

1

我只是想,因爲當我開始使用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 
      } 
     }); 
    }); 
+0

我必須做一個循環來獲得所有的產品嗎?有沒有辦法在控制器中操作json,所以它返回例如字符串中所有產品名稱的product.name? – lostdong12 2014-11-20 22:05:37

+0

如前所述,您可以使用JQuery每個循環遍歷值。那麼你可以訪問像product.id,product.name等東西... – 2014-11-20 22:07:20

+0

@ lostdong12看看我的例子我已經添加了如何訪問屬性。 – 2014-11-20 22:14:39

相關問題